我需要將 html 正文的所有 #text 元素用作陣列。富文本可以有不同的層次,所以我需要到達最低的元素。例如,對于下面的文本,我期望有一個包含 8 個元素的陣列。

獲取#文本節點的名稱或標簽或方法是什么?
uj5u.com熱心網友回復:
您可以遞回地掃描節點并將文本節點推送到陣列中。
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>
uj5u.com熱心網友回復:
您需要指定第一個父標簽并使用 innerText 屬性。
<script>
var text = document.getElementsByTagName("body")[0].innerText;
console.log(text.replace(/(\r\n|\n|\r|\t|\s)/gm, ''));
</script>
或者如果你想使用 jquery ,你可以這樣做。
console.log($("body span").text().replace(/(\r\n|\n|\r|\t)/gm, ''));
uj5u.com熱心網友回復:
//find the textnode like this//
const textNodes=document.querySelector("content");
//[put on a variable]//
//using this statement //
Array.from(textNodes).map((content)=>{
//now add eventlistener//
content.addEventListener("//event type//",functionHandler);
});
function functionHandler(e){
//do anything what you need//
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475601.html
標籤:javascript dom
下一篇:在輸入時執行搜索?
