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