我对 childNodes
有如下问题:
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
//childNodes.length = 7
但是
<ol><li> Coffee </li><li> Tea </li><li> Coca Cola </li></ol>
//childNodes.length = 3
似乎每个 \n
或 textnode
都被认为是一个 child
,我如何从 childNodes
中删除这些?
最佳答案
您可以使用 nodeType
检查给定的子 Node 是否为文本 Node 。文本 Node 的 nodeType
为 3
。我们可以使用号码或 the constant Node.TEXT_NODE
检查。
window.onload = function() {
var el = document.getElementsByTagName('ol')[0].childNodes; // using [0] as there is only one ol in the demo
console.log('Print with text nodes');
for (var i = 0; i < el.length; i++) { // will output all nodes with "undefined" for text nodes
console.log(el[i].innerHTML);
}
console.log('Print without text nodes');
for (var i = 0; i < el.length; i++) { // will output only non text nodes.
if (el[i].nodeType != Node.TEXT_NODE) // or if (el[i].nodeType != 3)
console.log(el[i].innerHTML);
}
}
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
关于javascript 检查子 Node 是元素还是文本 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24971177/