MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

JavaScript: Navigating DOM Tree: previousSibling nextSibling childNodes firstChild lastChild parentNode

Xah Lee,

This page is a tutorial of JavaScript navigating the DOM tree. This page show examples of using methods: {previousSibling nextSibling childNodes firstChild lastChild parentNode}.

Get Previous/Next Sibling

‹node›.previousSibling Return the previous sibling of ‹node›, or null if it doesn't exist.

‹node›.nextSibling Return the next sibling of ‹node›, or null if it doesn't exist.

When the sibling does not exist, the return value is null.

test code: JavaScript test page: nextSibling

Whitespace Nodes

Note: in most browsers, any space in HTML source code between tags are considered a node too. This is by W3C spec. So, typically, when you call nextSibling, you'll get a text node of whitespace. This is usually not what you want.

Here's a example. In the following, we get a node's next sibling, and get its node type. If the nodeType is 3, it means text node, and thus it's (probably) just white space. If node type is 1, then it's element.

alert(document.getElementById("a").nextSibling.nodeType);

Test page: JavaScript test page: nextSibling is whitespace node?

You can avoid the whitespace node problem by not having space or newline between your element's tags. example

<!doctype html><html><head><title>test</title></head><body><p>something</p></body></html>

Of course, this is not practical, because it makes the HTML hard to read.

Get Child Nodes

‹node›.childNodes Return all children of ‹node› as a list.

Suppose this is your HTML:

<div id="A">
some <span id="B">thing</span>
</div>

This is your JavaScript code:

var xx = document.getElementById("A").childNodes;

var num = xx.length;

alert("total children: " + num);
alert("first child node name: " + xx[0].nodeName);
alert("second child node name: " + xx[1].nodeName);
alert("3rd child node name: " + xx[2].nodeName);
total children ⇒ 3
first child node name ⇒ #text
second child node name ⇒ SPAN
3rd child node name ⇒ #text

Test page: JavaScript test page: childNodes

Source developer.mozilla.org

Get First/Last Child

‹node›.firstChild Return the first child of ‹node›.

‹node›.lastChild Return the last child of ‹node›.

Get Parent Node

‹node›.parentNode Return the parent of ‹node›.

blog comments powered by Disqus