我需要将 html 正文的所有 #text 元素用作数组。 富文本可以有不同的级别,所以我需要到达最低的元素。 例如,对于下面的文本,我期望有一个包含 8 个元素的数组。
获取#文本节点的名称或标签或方法是什么?
最佳答案
您可以递归地扫描节点并将文本节点推送到数组中。
const textNodes = []
function pushTextNode(node) {
if (node.nodeName === "#text") {
const nodeVal = node.nodeValue.trim();
if (nodeVal) {
textNodes.push(nodeVal);
}
return;
}
node.childNodes.forEach((childNode) => {
pushTextNode(childNode)
});
}
pushTextNode(document.querySelector("#root"));
console.log(textNodes);
<div id="root">
<span>
0
<b>
12<u>3</u>
</b>
<u>
4<b>5</b>
</u>
<b>67</b>8<a href="#">9</a>
</span>
</div>
关于javascript - 如何获取 html 树的 #text 节点数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72250407/