Getting all nodes inside a tag

こ雲淡風輕ζ 提交于 2019-12-08 03:37:31

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>

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.

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()
 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.

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