如何获取html树的#text节点数组

问题描述 投票:0回答:4

我需要将 html 正文的所有 #text 元素用作数组。 富文本可以有不同的级别,所以我需要到达最低的元素。 例如,对于下面的文本,我期望有一个包含 8 个元素的数组。

enter image description here

获取 # 文本节点的名称或标签或方法是什么?

javascript dom
4个回答
3
投票

您可以递归地扫描节点并将文本节点推入数组中。

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>


1
投票

您需要指定第一个父标签并使用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, ''));

1
投票
//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//
}

0
投票

最简单的方法是使用Xpath,下面的表达式返回给你所有有文本的节点

//*[string-length(text())>0]

如果您只想获取所有文本,请使用以下

//text()
© www.soinside.com 2019 - 2024. All rights reserved.