previousSibling and nextSibling

In this chapter you will learn:

  1. How to get the previous sibling and next sibling
  2. Deal with null sibling value

previousSibling and nextSibling properties

It's possible to navigate from one node in the list to another by using the previousSibling and nextSibling properties.

<!DOCTYPE html><!--   ja v  a2 s  .  c o m-->
<html>
    <body>
        <div id="div1">
            <p>Hello <b>World!</b></p>
            <ul>
                <li>List item 1</li>
                <li>List item 2</li>
                <li>List item 3</li>
            </ul>
        </div>
        <p>Hello <b>World!</b></p>
        <script type="text/javascript">
               var div = document.getElementById("div1");
               var node = div.nextSibling;
               document.writeln(node);
               node = div.previousSibling;
               document.writeln(node);
        </script>
    </body>
</html>

Click to view the demo

Null sibling value

The first node in the list has null for the value of its previousSibling property. The last node in the list has null for the value of its nextSibling property.

Hello World!

  • List item 1
  • List item 2
  • List item 3

Hello World!

If there's only one child node, both nextSibling and previousSibling will be null.

Next chapter...

What you will learn in the next chapter:

  1. How to get the last child and first child
  2. How to use length value to get the last child
  3. Deal with the single child with firstChild and lastChild
Home » Javascript Tutorial » DOM
Document Object Model
Node Type
nodeName and nodeValue
childNodes
parentNode
previousSibling and nextSibling
lastChild and firstChild
appendChild
insertBefore
ownerDocument
removeChild
replaceChild
Text
NodeList Length
DOM classes