Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get cells of a table row TR

I want to manipulate table cells with javascript, and so far I managed to get into tr-s, by using:

var as = document.getElementById('answers['+id+']');
var trs = as.getElementsByTagName("tr");
for (var i in trs)
{ ... }

UPDATE: The as variable contains a reference to the table.

Inside of the for cycle I wanted to go on the same login line and I have tried:

var tds = trs[i].getElementByTagName("td");

The problem is that on debugging I get the following error:

Uncaught TypeError: Object #<HTMLTableRowElement> has no method 'getElementByTagName' .

How could I get into the td-s of the tr-s?

like image 445
Ervin Avatar asked Apr 11 '11 11:04

Ervin


2 Answers

its getElementsByTagName and not getElementByTagName

var as = document.getElementById('answers['+id+']');
for(var i=0;i<as.rows.length;i++) {
    var trs = as.getElementsByTagName("tr")[i];
    var cellVal=trs.cells[0]
}

the variable cellVal will give the reference to the first cell or <td> similarly do for all the cells by increasing the index or putting it in a loop would make it dynamic...

like image 163
Sangeet Menon Avatar answered Sep 20 '22 18:09

Sangeet Menon


Check spelling of the method you are using to get td i.e.getElementByTagName

It should be getElementsByTagName. This should work fine as the way you are trying to fetch.

Check Manipulating the table with DOM and CSS for more info.

like image 40
niksvp Avatar answered Sep 24 '22 18:09

niksvp