Loop through table cells

I need to know how to loop through tables and read the results. I suspect there needs to be two loops that are nested: one for tr, and one for td. Here’s the html:

    <table id ="my_table">
                                <td>tr1, cell1</td>
                                <td>tr1, cell2</td>
                                <td>tr1, cell3</td>
                                <td>tr1, cell4</td>
                                <td><input type ="text" size ="3" value ="1"/></td>
                                <td>tr2, cell1</td>
                                <td>tr2, cell2</td>
                                <td>tr2, cell3</td>
                                <td>tr2, cell4</td>
                                <td><input type ="text" size ="3" value ="1"/></td>
                                <td>tr3, cell1</td>
                                <td>tr3, cell2</td>
                                <td>tr3, cell3</td>
                                <td>tr3, cell4</td>
                                <td><input type ="text" size ="3" value ="1"/></td>

Here’s my progress in JS:

var table = document.getElementById("my_table");
var rows = my_table.getElementsByTagName("tr");
var th = my_table.getElementsByTagName("th")

    var td = my_table.getElementsByTagName("td");
    	var current_td = td[3].firstChild.nodeValue;
    	var current_value = th[3].firstChild.nodeValue;

When I alert the values, I get the first row of th and the first row of td.


I tried several for-loops, but I just can’t get it right.

    for(var i = 1; i < rows.length; i++) {
    		var cells = rows.length[i].nodeValue;
    		alert(cells); /* nothing happens */

Please help me with the logic. I tried to find the answer in other places, including stock overflow, but the closest I got was a reply for Jquery.

Here’s the link to the Jquery answer: http://stackoverflow.com/questions/14591538/javascript-looping-through-all-cells-in-table

Is that the kind of logic that is applicable here?

Why are you using getElementsByTagName instead of simply getting the table tag and then using the tbodies, rows, and cells properties that the returned table has to reference everything else in the table.

Apart from the table tag itself the only other table related tag you need to use regular DOM calls instead of the special table ones is when creating a tbody tag.

1 Like

Because I’m a n00b. I wasn’t even aware that the table objects returned these methods. Thanks for pointing me in the right direction.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.