Node Properties and Methods
<body>
<ol id="ol1">
<li id="li1">
<span id="span1">
This is Text 1
</span>
</li>
<li id="li2">
<span id="span2">
This is Text 2
</span>
</li>
<li
id="li3">
<span id="span3">
This is Text 3
</span>
</li>
</ol>
</body>
hasChildNodes() returns a Boolean value of true
or false if the node has child nodes. For instance, if we said:
document.getElementById("span3").hasChildNodes()
that would return true, but if we said:
document.getElementById("span3").firstChild.hasChildNodes()
it would return false because that doesn't have any children (a text node can
never have any children).
nodeName returns the "name" of a node:
document.getElementById("span3").nodeName
returns "SPAN"
tagName returns the tagName of an element.
document.getElementById("span3").tagName
returns "SPAN"
You may be asking yourself what's the difference between nodeName and tagName. Well, if you access a text node's tagName, there is no tagName because it's not a tag (this only works for elements), but if you access a text node's nodeName, it will give you "#text." Thus:
document.getElementById("span3").firstChild.nodeName returns "#text" while document.getElementById("span3").firstChild.tagName returns "undefined."
nodeType tells you what type of node an element is. It returns 1, 2, or 3.
- It returns 1 if it's an element
- It returns 2 if it's an attribute
- It returns 3 if it's text
document.getElementById("span3").nodeType
returns 1, while
document.getElementById("span3").firstChild.nodeType
returns 3. We won't really examine a nodeType of
2 in this tutorial as it could get a little complicated.
nodeValue returns value of the node. You can use
this to retrieve or change this value. If the node is a text node (nodeType
of 3), it returns the text; if it is an attribute (nodeType
of 2), it returns the value of that attribute; if it's an element (nodeType
of 1), it returns null. Text will return it's value:
document.getElementById("span3").firstChild.nodeValue
returns "This is Text 3," while an element returns null:
document.getElementById("span3").nodeValue
returns null.
Now, let's learn about attributes.
