tags:

views:

35

answers:

4

What is it I am doing wrong here:

When I try to use the getttribute['id'] method on a TableCell object that I get from iterating through a tables rows/cells it returns undefined:

var rows = document.getElementById["table"].rows;
var cells;
for(var i=0; i < rows.length; i++) {
 cells = rows[i].cells
 for(var j=0; j < cells.length; j++) {
  alert(cells[j].innerHTML); //returns Cell1
  alert(cells[j].getAttribute["id"]); //returns undefined
  alert(document.getElementById["c1"].innerHTML); //returns Cell1

 }
}

This is example HTML:

    <table id="table">
    <tbody>
        <tr>
         <td id="c1">Cell1</td>
        </tr>
    </tbody> 
</table>

Question is why does the getAttribute method return undefined for all attributes when accessed through cells[j]?

+1  A: 

getAttribute is a method and you are using it as an indexer

Use

alert(cells[j].getAttribute("id"));

Also replace

document.getElementById["table"].rows;

with

document.getElementById("table").rows;

and

document.getElementById["c1"].innerHTML

with

document.getElementById("c1").innerHTML

getElementById is also a method.

rahul
A: 

I don't know why, but getAttribute doesn't like the id attribute. Use cells[j].id instead.

tmim
A: 

Simply use cells[j].id to get the id of the cell.

Kangkan
+1  A: 

You are using square brackets [] instead of parentheses () in calls to getElementById and getAttribute

//change

getElementById["table"]
getAttribute["id"]
getElementById["c1"]

//to

getElementById("table")
getAttribute("id")
getElementById("c1")

//Respectively.
Amarghosh
Yes that's true, it is a method! Thanks
Nam of 86