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

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

What is the best way to adjust the height of the border on the left

Is it possible to add a border-left with height to only one attribute, such as h4? I want to add a border on the left side with a specific height, but the title prohibits adding the height property directly. Can anyone offer guidance on how to achieve th ...

Steps to retrieve the central coordinates of the displayed region on Google Maps with the Google Maps JavaScript API v3

Is there a way to retrieve the coordinates for the center of the current area being viewed on Google Maps using JavaScript and the Google Maps JavaScript API v3? Any help would be greatly appreciated. Thank you! ...

AngularJS provides a way to create opening pages with clickable buttons for a

I'm struggling to implement buttons that switch ons-templates when clicked. I've been following this example as a reference: Here's the code snippet I've been working on, but it just won't cooperate: <!doctype html> &l ...

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...

Tips for consolidating outputs from three different APIs using JavaScript and AJAX? [Pseudo code example]

For my school project, I am working on an e-commerce aggregator site where I need to combine product data from 3 different APIs (like Aliexpress and Amazon) into one homepage. Although I can retrieve results from each API individually, I'm facing chal ...

Fixed Positioning Div to Stay at the Top while Scrolling

Currently, I have successfully implemented the functionality to stick the div to the top once it scrolls down by 320px. However, I am curious if there is an alternative approach to achieving this effect. Below is the code snippet I am using: jQuery(functi ...

What causes an object to declare itself as undefined only in the event that I attempt to access one of its properties?

Check out this snippet of code: req.Course.find({}).populate('students', 'username firstName lastName registered').populate('teacher', 'image mID firstName lastName').sort({title: 1}).exec(function(err, courses){ ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Leverage PHP to integrate JSON data for consumption by JavaScript

I've been exploring the integration of React (JavaScript) within a WordPress plugin, but I need to fetch some data from the database for my plugin. While I could retrieve this data in JavaScript using jQuery or an API call, because the data will remai ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

Is there a way to save a base64 image to an excel file?

I need assistance with exporting Excel Charts from NVd3 using Angularjs. Here is the code I have been trying: (jsfiddle) <button id="myButtonControlID">Export Table data into Excel</button> <div id="divTableDataHolder"> <table> ...

Determine whether to show or hide a div based on the width of the

Is there a way to dynamically hide a div using Bootstrap 4 based on the screen width? Can this be achieved without using JavaScript? I am particularly interested in hiding certain text elements that are not relevant on smaller screens, such as mobile de ...

Interactive bar chart that updates in real-time using a combination of javascript, html, and

Current Situation: I am currently in the process of iterating through a machine learning model and dynamically updating my "divs" as text labels. My goal is to transform these values into individual bars that visually represent the values instead of just d ...

Adjusting solely the depicted data sets in the Highcharts.js library

I have a spline chart with 10 different curves on it - When the page is first loaded, none of the charts are visible as I have set "visible" to false. Users will then click on the curve(s) they want to see. I am looking for a way to dynamically change the ...

Steps for creating a JavaScript session expiry notification:

Ensuring user session continuity is essential, especially before it expires. In a recent quest on Stack Overflow, I inquired about detecting a dead session and alerting the user. A solution involving AJAX/JSON was proposed, but it inadvertently kept the s ...

Make an element in jQuery draggable but always within the viewport

My issue is that when I resize the window, the element stays in its position until I start dragging it. Once I drag it and then resize the window again, it doesn't stay within its container. To better illustrate my problem, you can view a demo on Fid ...

The challenge of transferring documents to the server

There is a form on the webpage where users can select a file and click a button to send it. <form enctype="multipart/form-data"> <input type="file" id="fileInput" /> <button type="button&quo ...