Ervin
Ervin

Reputation: 2442

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?

Upvotes: 8

Views: 69344

Answers (2)

Sangeet Menon
Sangeet Menon

Reputation: 9905

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...

Upvotes: 20

niksvp
niksvp

Reputation: 5563

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.

Upvotes: 3

Related Questions