5

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?

InteXX
  • 5,804
  • 5
  • 33
  • 54
Ervin
  • 2,244
  • 3
  • 30
  • 43
  • possible duplicate of [this](http://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript) – richaux Apr 11 '11 at 11:42

2 Answers2

15

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

Lawrence Dol
  • 59,198
  • 25
  • 134
  • 183
Sangeet Menon
  • 8,737
  • 8
  • 37
  • 56
  • 6
    No need for getElementsByTagName at all. Tables have a rows collection, and rows have a cells collection, so rows = table.rows and the cells for each row is cells = rows[i].cells. – RobG Apr 11 '11 at 13:04
3

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.

niksvp
  • 5,425
  • 2
  • 22
  • 40