previousSibling and nextSibling
In this chapter you will learn:
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>
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:
- How to get the last child and first child
- How to use length value to get the last child
- Deal with the single child with firstChild and lastChild