简体   繁体   English

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

[英]How can I get array of #text nodes of the html tree

I need to use all the #text elements of an html body as an array.我需要将 html 正文的所有 #text 元素用作数组。 The rich text can have various levels so I need to get to the lowest element.富文本可以有不同的层次,所以我需要到达最低的元素。 For example for the text below I'm expecting to have an array of 8 elements.例如,对于下面的文本,我期望有一个包含 8 个元素的数组。

在此处输入图像描述

What is the name or tag or method to get the # text node?获取#文本节点的名称或标签或方法是什么?

You can recursively scan through the nodes and push the text nodes into an array.您可以递归地扫描节点并将文本节点推送到数组中。

 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>

You need to specify the first parent tag and use innerText attribute.您需要指定第一个父标签并使用 innerText 属性。

<script>
var text = document.getElementsByTagName("body")[0].innerText;
console.log(text.replace(/(\r\n|\n|\r|\t|\s)/gm, ''));
</script>

or if you want to use jquery , you can do like this.或者如果你想使用 jquery ,你可以这样做。

console.log($("body span").text().replace(/(\r\n|\n|\r|\t)/gm, ''));
//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//
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM