本文介绍了获取标签内的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

<div id="container">
Lorem ipsum dolor sit amet
<p>This is a paragraph</p>
<br />
<span>This is a span</span>
Lorem ipsum dolor sit amet
</div>

是否可以在此div中获取所有文本节点和标签?我想通过数组访问每个节点(包括文本).

Is it possible to get all text nodes and tags inside this div? I want to access each node (including texts) via an array.

例如:

for(var i=0;i<nodesArray.length;i++)
{
    document.write("Node: "+nodesArray[i]+"<br />");
}

输出:

Node: Lorem ipsum dolor sit amet
Node: This is a paragraph
Node: This is a span
Node: Lorem ipsum dolor sit amet

我在jquery中尝试了所有选择器",但它只获得标签,而不是文本.

I tried "all selector" in jquery but it gets only tags, not texts..

推荐答案

您可以使用以下代码执行此操作.基本上,childNodes获取作为元素子级的所有节点的列表.然后,我们必须遍历整个获取的节点列表,然后根据需要打印输出.

You can use the below code to do this. Basically the childNodes gets a list of all nodes that are children of the element. Afterwards, we have to traverse the entire fetched node list and then print the output as required.

children[i].textContent.trim() != ""上的if条件用于排除空节点(包括<br/>标签).

The if condition on children[i].textContent.trim() != "" is used to exclude empty nodes (including <br/> tags).

window.onload = function() {
  var children = document.getElementById("container").childNodes;
  for (var i = 0; i < children.length; i++) {
    if (children[i].textContent.trim() != "")
      document.getElementById("output").innerHTML += "Node: " + children[i].textContent + "<br/>";
  }
}
<div id="container">
  Lorem ipsum dolor sit amet
  <p>This is a paragraph</p>
  <br />
  <span>This is a span</span>
  Lorem ipsum dolor sit amet
</div>

<hr>
<h3>Output</h3>

<div id="output">

</div>

这篇关于获取标签内的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 20:53