admin管理员组文章数量:1310143
I have this simple example
<table border="1px">
<tr>
<td> </td>
<td> <input type="button" value="Click" onclick="insertText()"/> </td>
</tr>
</table>
I wanted to get the first td element of the (first) tr element, I tried:
var td = document.getElementsByTagName("table")[0].children[0].children[0];
Because it's:
var td = document.getElementsByTagName("table")[0]
for the table element itselfchildren[0]
for the tr element- and
children[0]
again for the first td element
That's what I thought, but apparently this returns me the tr element and only adding another .children[0]
got me the td element.
var td = document.getElementsByTagName("table")[0].children[0].children[0].children[0];
Why is that, or what have I missed here?
I have this simple example
<table border="1px">
<tr>
<td> </td>
<td> <input type="button" value="Click" onclick="insertText()"/> </td>
</tr>
</table>
I wanted to get the first td element of the (first) tr element, I tried:
var td = document.getElementsByTagName("table")[0].children[0].children[0];
Because it's:
var td = document.getElementsByTagName("table")[0]
for the table element itselfchildren[0]
for the tr element- and
children[0]
again for the first td element
That's what I thought, but apparently this returns me the tr element and only adding another .children[0]
got me the td element.
var td = document.getElementsByTagName("table")[0].children[0].children[0].children[0];
Why is that, or what have I missed here?
Share Improve this question edited Oct 6, 2013 at 19:31 James A Mohler 11.1k15 gold badges50 silver badges76 bronze badges asked Jul 17, 2013 at 16:12 Big_ChairBig_Chair 3,2393 gold badges35 silver badges67 bronze badges1 Answer
Reset to default 10That's because you're forgetting about the <tbody>
element, which is automatically inserted into the DOM.
What your table really looks like:
<table border="1px">
<tbody>
<tr>
<td> </td>
<td> <input type="button" value="Click" onclick="insertText()"/> </td>
</tr>
</tbody>
</table>
Hence why you needed to dig down through three levels of children to target the <td>
element you wanted.
Side note: If you'd like to know more about why the <tbody>
element is automatically injected into <table>
elements if undeclared, see this question and its answers.
本文标签: javascriptgetElementsByTagName(quottablequot)getting td on curious wayStack Overflow
版权声明:本文标题:javascript - getElementsByTagName("table") - getting td on curious way - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741848774a2400935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论