Reputation: 9452
Assuming I have some HTML with untagged content, e.g:
<html>
<body>
<p>text in a tag</p>
other text outside any tag
</body>
</html>
How can I get to the untagged element? Even document.getElementsByTagName('*') does not contain the untagged element.
TIA
Upvotes: 4
Views: 550
Reputation: 17579
Just in your case you can do simply
document.getElementById('body').lastChild
However in a more general case you need to loop through children and check for
a = document.getElementById('body').lastChild
console.log(a.nodeType) // 3
console.log(a.nodeName) // #text
Here is example on jsfiddle
Upvotes: 3
Reputation: 3788
I would suggest using the .nodeType
attribute which will return an integer value depending on the type of node returned. Text nodes return a value of 3. Element nodes return a value of 1 be warned however the Text inside your <p>
counts as its own node with a nodeType of 3.
With this in mind if your looking for textNodes that are children to your body element something along the following lines should work.
var nodes = document.getElementByTagName('body').childNodes
for (i=0; i < nodes.length; i++)
{
if(nodes.childNode[i].nodeType == 3)
{
//THIS NODE IS A TEXT NODE OF THE BODY ELEMENT
//DO WHAT YOU NEED WITH IT
}
}
Upvotes: 1