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

Perm URL with updates:

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

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.


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. e.g.

<!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.


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

Suppose this is your HTML:

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

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


firstChild lastChild

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

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


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

Popular posts from this blog

11 Years of Writing About Emacs

does md5 creates more randomness?

Google Code shutting down, future of ErgoEmacs