Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first cell of table rows with querySelectorAll()

I am attempting to target a table by its data attribute value. I would then like to find the first <td> of every <tr> in that table, and add a class to each <td> that is selected.

I attempted the following, however I am stuck in understanding the source of my error:

var mprimary = document.querySelectorAll("[data='regMultipleTable']");
for (var i = 0; i < mprimary.rows.length; i++) {
   var firstTD = mprimary.rows[i].cells[0];
   firstTD.className = 'your-the-first';
}

My table looks like this:

<table data="regMultipleTable">
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tbody>
</table>

I want to target the td with values 1, 4, 7, etc... Please help

like image 741
klewis Avatar asked Oct 17 '25 06:10

klewis


2 Answers

You could simplify your logic by using the following selector:

table[data='regMultipleTable'] td:first-child

This selector means, "select the first td of every parent (row) in the table with data attribute of 'regMultipleTable'".

In code, this could look like:

var mprimary = document
.querySelectorAll("table[data='regMultipleTable'] td:first-child");

for (var node of mprimary) {
  
  node.classList.add("your-the-first");
}
.your-the-first {
  background:yellow;
}
<table data="regMultipleTable">
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
  </tr>
</table>
like image 99
Dacre Denny Avatar answered Oct 19 '25 21:10

Dacre Denny


querySelectorAll() returns a list of all the tables with that data attribute.

If there can be multiple such tables, you need to loop over them.

var mprimary = document.querySelectorAll("[data='regMultipleTable']");
mprimary.forEach(function(mprimary) {
  for (var i = 0; i < mprimary.rows.length; i++) {
    var firstTD = mprimary.rows[i].cells[0];
    firstTD.className = 'your-the-first';
  }
});

If there should only be one table, just use querySelector instead of querySelectorAll. It returns that single element instead of a list.

like image 24
Barmar Avatar answered Oct 19 '25 21:10

Barmar