Undefined id property on td object when accessed through rows/cells collection
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 开发者_StackOverflowattributes when accessed through cells[j]?
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.
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.
I don't know why, but getAttribute
doesn't like the id attribute. Use cells[j].id
instead.
Simply use cells[j].id to get the id of the cell.
Alternately you can use the getAttribute method:
xmlDoc.getElementsByTagName("sec")[0].getAttribute("id")
Here I'll get back s1
for a tag like <sec id="s1">
.
精彩评论