Reputation: 1633
I'm little confused about properties of text nodes in JavaScript. Let say that I have this piece of html:
<html lang="en-US">
<head>
<title>JavaScript test</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body onload="load()">
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
<ul>
<li>1.</li>
<li>2.</li>
</ul>
</body>
And onload()
function:
function load()
{
var bodyChildren = document.childNodes[0].childNodes;
for(var i = 0; i < bodyChildren.length; i++)
{
alert(bodyChildren[i].nodeType
+ ": " + bodyChildren[i].nodeName
+ ": " + bodyChildren[i].nodeValue);
}
}
This http://www.w3schools.com/js/js_htmldom_navigation.asp tells: "nodeValue for text nodes is the text itself", but I'm getting this output:
3: #text:
1: DIV: null
3: #text:
1: UL: null
3: #text:
Can you explain me why nodeValue
returns null
for element node
and "nothing" for text node
?
Edit: The stuff about white spaces is nicely described here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM
Upvotes: 0
Views: 894
Reputation: 318182
That's what nodeValue
does according to the specification, it returns this
Comment - content of the comment
Document - null
DocumentFragment - null
DocumentType - null
Element - null
NamedNodeMap - null
EntityReference - null
Notation - null
ProcessingInstruction - entire content excluding the target
Text - content of the text node
Note that it returns null
for anything but comments, textNodes and processing instruction, for all other node types null
is explicitly returned.
To get the text content of an Element node, use textContent
(innerText
for older IE), to get the HTML of an Element node, use innerHTML
Upvotes: 3
Reputation: 664246
why nodeValue returns
null
for element node
Because element nodes don't have values. They basically only have a name, attributes and children.
…and "nothing" for text node?
It does return you something: the whitespace between those element nodes.
Upvotes: 2