Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through td in a tbody?

Tags:

javascript

dom

<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

like image 488
NOOB_USER Avatar asked Mar 06 '14 06:03

NOOB_USER


2 Answers

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

like image 61
Praveen Avatar answered Sep 19 '22 22:09

Praveen


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');
like image 38
rink.attendant.6 Avatar answered Sep 22 '22 22:09

rink.attendant.6