Focus on selecting each label within a table using JavaScript

In my current setup, I am attempting to customize radio buttons and checkboxes.

Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{
  var mark=document.createElement("span");
  Array.from(tr.querySelectorAll("input")).forEach((inp,index1)=>{
    if(inp.type=="radio"){
      mark.classList.add("dotmark");
      inp.parentNode.appendChild(mark);
    }
    else{
      mark.classList.add("checkmark");
      inp.parentNode.appendChild(mark);//instead append in to the next td's label tag
    }
  })
})
span{
width:20px;
height:20px;
background:#ccc;
display:inline-block;
}
<table id="tab1" class="table labelCustom">
   <tbody>
        <tr><td><input type='radio' id='one' name='name'></td><td><label for='one'>example</label></td></tr>
        <tr><td><input type='radio' id='two' name='name'></td><td><label for='two'>example</label></td></tr>
        <tr><td><input type='radio' id='three' name='name'></td><td><label for='three'>example</label></td></tr>
   </tbody>
</table>

I would like the dynamically created span element to be inserted into the label tag instead of within the input's td.

Note: The class of the span element depends on the input type.

Answer №1

One recommended method involves the following steps:

Array.from(document.querySelectorAll("tr")).forEach((tr, index) => {
  var mark = document.createElement("span");
  Array.from(tr.querySelectorAll("input")).forEach((inp, index1) => {

    // Storing the <label> element for better readability:
    let label = inp.parentNode.nextElementSibling.querySelector('label');

    // Adding a specific class based on the input type:
    mark.classList.add(inp.type === 'radio' ? 'dotmark' : 'checkmark');

    // Appending the created element to the label section:
    label.appendChild(mark);
  })
})
span {
  width: 20px;
  height: 20px;
  background: #ccc;
  display: inline-block;
}

span.dotmark {
  background-color: limegreen;
}

span.checkmark {
  background-color: #f90;
}
<table id="tab1" class="table labelCustom">
  <tbody>
    <tr>
      <td><input type='radio' id='one' name='name'></td>
      <td><label for='one'>example</label></td>
    </tr>
    <tr>
      <td><input type='radio' id='two' name='name'></td>
      <td><label for='two'>example</label></td>
    </tr>
    <tr>
      <td><input type='radio' id='three' name='name'></td>
      <td><label for='three'>example</label></td>
    </tr>
    <tr>
      <td><input type='checkbox' id='four' name='differentName'></td>
      <td><label for='four'>example</label></td>
    </tr>
  </tbody>
</table>

Additionally, an important point raised by the OP in response to the question:

I attempted using nextSibling with no success, but nextElementSibling worked effectively.

The key disparity between the two methods is that while nextSibling includes any sibling regardless of its type, nextElementSibling specifically targets the next sibling which is also an element.

For more information, please refer to the following resources:

Answer №2

Utilize

inp.parentNode.nextElementSibling.querySelector('label')

instead of simply using

inp.parentNode

Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{
  var mark=document.createElement("span");
  Array.from(tr.querySelectorAll("input")).forEach((inp,index1)=>{
    if(inp.type=="radio"){
      mark.classList.add("dotmark");
      inp.parentNode.nextElementSibling.querySelector('label').appendChild(mark);
    }
    else{
      mark.classList.add("checkmark");
      inp.parentNode.nextElementSibling.querySelector('label').appendChild(mark);
    }
  })
})
span{
width:20px;
height:20px;
background:#ccc;
display:inline-block;
}
<table id="tab1" class="table labelCustom">
   <tbody>
        <tr><td><input type='radio' id='one' name='name'></td><td><label for='one'>example</label></td></tr>
        <tr><td><input type='radio' id='two' name='name'></td><td><label for='two'>example</label></td></tr>
        <tr><td><input type='radio' id='three' name='name'></td><td><label for='three'>example</label></td></tr>
   </tbody>
</table>

Answer №3

A more efficient way to handle this situation is by eliminating the need for nested loops. Since there is only one input and label inside each tr element, you can streamline the process by combining them into a single query using tr input. Additionally, there is no requirement to utilize Array.from as querySelectorAll already returns a NodeList with a built-in forEach function.

document.querySelectorAll('tr input').forEach(input => {
    const span = document.createElement('span');
    span.classList.add(input.type === 'radio' ? 'dotmark' : 'checkmark');
    input.parentNode.nextElementSibling.appendChild(span);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining a string value through a promise retrieval

Within the following code snippet, I am executing an HTTP request where I extract a "token" (a string) from the response. My objective is to assign this token value to the variable foo. foo = request.post( { url: 'http://10.211.55 ...

The Google Visualization chart fails to display properly once CSS is applied

Struggling with a graph display issue here. It's quite perplexing as it works fine on older laptops and Safari, but not on Chrome or older versions of Firefox. Works like a charm on my old laptop and Safari, but fails on Chrome and Firefox (haven&apo ...

Parent div is positioned absolutely with overflow set to hidden

I am facing a unique requirement where the parent div has an absolute position and the child div also has an absolute position. Inside the parent div, I have set overflow: hidden to hide the extra width of the child div. However, this setup is not working ...

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

Multer is successfully retrieving images, but unfortunately, it is failing to save the files in the intended directory

I am currently facing an issue with my Express server. The problem arises when a user attempts to make a post request for their profile, including a profile picture submission. I have set up Multer to handle the image upload process and store the photo in ...

Struggling with getting the JavaScript, scss, and CSS television animation to turn on and off properly? Seeking assistance to troubleshoot this

After finding this javascript code on Codepen and seeing that it worked perfectly in the console there, I tried to run it on my computer with jQuery but it didn't work outside of Codepen. Even when attempting to use it on JSfiddle or compile the SCSS ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Integrating Watson Conversation with Oracle Database

Hello everyone, I am currently working on a project where I need Watson to fetch a response manually set from our Oracle Databases. To achieve this, I am using async to access the database sequentially and return the response. Initially, I faced an issue ...

Tips for updating the background color of a dropdown menu in the navigation bar

I am attempting to increase the size of the dropdown menu and change its background color. Currently, I can only modify the color of the links and the surrounding area. .navbar a { width: 125px; text-align: center; ...

Get rid of the paper border in Material-ui

Is there a way to remove the top border in material-ui Paper component? I've attempted the code below, but it doesn't seem to be effective. <Paper sx={{ border: 0, borderTop: 0, borderRadius: 0, ...

Using JSP to send variables from an external Javascript file

After creating a timer function, I am looking to display the results on a different page. The setup involves a JSP file calling functions from a separate JS file in order to output the information to another screen: Instructions in the JSP file: <butt ...

Transferring account information to a function call in the near-js-api

I am attempting to utilize the following method in near-js-api for my contract. It requires a Rust AccountId as input. What is the correct procedure to serialize an Account and send it to the contract? Also, are there any specific considerations when inv ...

I rely on the handleChange function to update the state value, but unfortunately, it remains unchanged

In my project, I am working on creating multiple responsive forms (form1, form2, and form3) within the same page using framer motion. However, I am facing an issue where the state value is not updating correctly when users fill out the form. Specifically, ...

Updating the state on a click event triggered by a MenuItem in React using Material UI

I'm currently working on implementing state changes based on dropdown selections using Material UI. However, I've encountered an issue where the code snippet below (simplified) only returns the list item, and I'm unsure what steps to take n ...

ways to set a background color for a textarea element using bootstrap

How can I add a background color to my text area field in Bootstrap? <div class="form-group"> <div class="col-xs-12"> <textarea class="form-control" id="exampleTextarea" rows="6" placeholder="Message" style="background-color: #f ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

Error: Unable to locate module '@material/core/Grid'

After cloning a repository that is built with MUI, I noticed that certain components were already imported and working seamlessly. These components include: import Card from '@mui/material/Card' import CardActions from '@mui/material/CardAct ...

"Interact with JSON data using AngularJS and JavaScript by clicking a button to edit

Here is my code in Plunker. Clicking on the Edit button should allow you to edit the details. Check out the full project here. <title>Edit and Update JSON data</title> <div> {{myTestJson.name}} <table><tbody> ...

Do you think it's achievable to modify the color using CSS's order attribute?

When I look at the code in Firefox's inspector, I notice this : element { order:35; } Can a color be assigned to it? I am customizing my year outlook calendar and have set a particular day to display in a different color. But when I click on the mo ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...