Javascript DOM HTML Node nextSibling Property

Introduction

Get the HTML content of the next sibling of a list item:

var x = document.getElementById("item1").nextSibling.innerHTML;

Click the button to get the HTML content of the next sibling of the first list item.

Whitespace inside elements is considered as text, and text is considered as nodes.

If you add whitespace between the two li elements, the result will be "undefined".

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Example list:</p>

<ul>
   <li id="item1">Coffee (first li)</li>
   <li id="item2">Tea (second li)</li>
</ul>//from www  .jav  a2  s. com
<button onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("item1").nextSibling.innerHTML;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

The nextSibling property returns the node immediately following the specified node, in the same tree level.

The returned node is returned as a Node object.

The nextSibling returns the next sibling node as an element node, a text node or a comment node.

The nextElementSibling returns the next sibling node as an element node ignoring text and comment nodes.

This property is read-only.

We can use the previousSibling property to return the previous node of the specified node in the same tree level.

We can use the childNodes property to return any child node of a specified node.

The nextSibling property returns a Node object representing the next sibling of the node, or null if there is no next sibling.




PreviousNext

Related