How to select <td> of the <table> with javascript?
This d = t.getElementsByTagName("tr")
and this r = d.getElementsByTagName("td")
are both arrays
. The getElementsByTagName
returns an collection of elements even if there's just one found on your match.
So you have to use like this:
var t = document.getElementById("table"), // This have to be the ID of your table, not the tag
d = t.getElementsByTagName("tr")[0],
r = d.getElementsByTagName("td")[0];
Place the index of the array as you want to access the objects.
Note that getElementById
as the name says just get the element with matched id, so your table have to be like <table id='table'>
and getElementsByTagName
gets by the tag.
EDIT:
Well, continuing this post, I think you can do this:
var t = document.getElementById("table");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<tds.length;n++)
{
tds[n].onclick=function() { alert(this.innerHTML); }
}
}
Try it!
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
needs to be:
var t = document.getElementById("table"),
tableRows = t.getElementsByTagName("tr"),
r = [], i, len, tds, j, jlen;
for ( i =0, len = tableRows.length; i<len; i++) {
tds = tableRows[i].getElementsByTagName('td');
for( j = 0, jlen = tds.length; j < jlen; j++) {
r.push(tds[j]);
}
}
Because getElementsByTagName
returns a NodeList
an Array-like structure. So you need to loop through the return nodes and then populate you r
like above.
try document.querySelectorAll("#table td");