HTML 表 DOM 创建了错误数量的子元素
我的代码中有一个表,我将其用作查找表,通过根据 的 id 从
获取一些值>。
<table>
<tr id="nas">
<td>1.34</td>
<td>0.67</td>
<td>1</td>
<td>1.25</td>
</tr>
</table>
当我如上所示输入表格并执行以下操作时: document.getElementById("nas").childNodes.length
结果是 9,而显然我只有 4 个子元素元素 。有些子元素是真正的带有值的
,有些只是空元素。我真的对这个感到困惑。
但是,如果我将表格全部输入一行,我就会得到正确的孩子数量。
<table>
<tr id="nas"><td>1.34</td><td>0.67</td><td>1</td><td>1.25</td></tr>
</table>
您认为为什么会发生这种情况?
I have a table in my code which I am using as a look-up table, by grabbing some values from <td>
based on the id of the <tr>
.
<table>
<tr id="nas">
<td>1.34</td>
<td>0.67</td>
<td>1</td>
<td>1.25</td>
</tr>
</table>
When I have my table typed-in as shown above and when I do: document.getElementById("nas").childNodes.length
the result is 9, while clearly I have only 4 child elements of the element <tr id="nas">
. Some of the child elements are real <td>
s with values, some are just empty elements.I am really confused with this one.
However if I type-in the table all in one line, I get the correct number of children.
<table>
<tr id="nas"><td>1.34</td><td>0.67</td><td>1</td><td>1.25</td></tr>
</table>
Why do you think this is happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我并不确切知道是谁制造了文本节点、浏览器还是 javascript 解析器,但这就是 javascript 所看到的。
I dont exactly know who makes the text nodes, the browser or javascript parser, but thats what javascript is seeing.
这里有一篇很好的文章解释了这个问题:
https://developer.mozilla.org/en/whitespace_in_the_dom
There is a good article explaining the problem here:
https://developer.mozilla.org/en/whitespace_in_the_dom
childNodes 包括所有子节点,包括文本节点(即单元格之间的空白)。尝试这样的事情:
childNodes includes ALL childNodes, include text nodes (i.e., the white-space in between your cells). Try something like this:
因为标签之间的换行符被视为文本,并被转换为 DOM 中的文本节点。
Because the newline between the tags is counted as text, and gets transformed into a text node in the DOM.