gpt4 book ai didi

javascript 检查子 Node 是元素还是文本 Node

转载 作者:IT老高 更新时间:2023-10-28 23:07:24 24 4
gpt4 key购买 nike

我对 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

似乎每个 \ntextnode 都被认为是一个 child ,我如何从 childNodes 中删除这些?

最佳答案

您可以使用 nodeType 检查给定的子 Node 是否为文本 Node 。文本 Node 的 nodeType3。我们可以使用号码或 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com