<table>
<tbody id="SAMPLETBODY">
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td>TEST3</td>
<td>TEST4</td>
</tr>
</tbody>
</table>
I have the code above, I want to iterate through the td's, since iterating through tbodies in a table is like this:
var table1 = document.getElementById('firstTable');
for(int i = 0; i < table1.tBodies.length; i++) {
/*DO SOMETHING HERE*/
}
How can I do it in td inside tbodies?
EDIT:
I have multiple tbodies in the table, I have already tried some codes that is similar (It iterated through all tbodies) and posted here before I asked the question.
EDIT AGAIN:
final code:
function sampleFunc() {
var x = "";
var tds = document.querySelectorAll('#SAMPLETBODY td'), i;
for(i = 0; i < tds.length; ++i) {
x = x + tds[i].innerHTML;
}
return x;
}
thanks to:rink.attendant.6
var table1 = document.getElementById('firstTable');
Here it returns table with id firstTable
Then using that get all td
within the table1 like
var tds = table1.getElementsByTagName('td');
Now you can iterate over each td like
for (i = 0; i < tds.length; i++) {
console.log(tds[i])
}
JSFiddle
Use querySelectorAll()
:
var tds = document.querySelectorAll('tbody td'), i;
for(i = 0; i < tds.length; ++i) {
// do something here
}
If you wish to restrict it to a certain table, for instance, #firstTable
, you will need to specify that:
var tds = document.querySelectorAll('#firstTable tbody td');
Just noticed that you have an ID on your tbody
, so the selector would look like this for your specific tbody
:
var tds = document.querySelectorAll('#SAMPLETBODY td');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With