Getting all nodes inside a tag

流过昼夜 提交于 2019-12-08 06:42:36

问题


I have a code like this:

<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>

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 example:

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

OUTPUT:

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

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


回答1:


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.

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>



回答2:


With jquery you can use the method .children() (http://api.jquery.com/children/) to get all children to the container div and than you get the value from each child and prints that.




回答3:


To get text contained in an element use the .text() function. for instance $('#container').text() or in this case

$("#container").find('*').add('#container').map(function() { return $(this).text }).get()



回答4:


 jQuery("#container").html() 

This will return all text and child elements but it will not return as an array as you expect. May be you can use this to verify and do what ever you want.



来源:https://stackoverflow.com/questions/18462894/getting-all-nodes-inside-a-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!