Javascript DOM HTML Element nextElementSibling Property

Introduction

The nextElementSibling property returns the element immediately following the specified element.

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

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

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

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  w  w  w  . j a v  a2 s . c o  m*/
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

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

</body>
</html>

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, not including text and comment nodes.

This property is read-only.

Use the previousElementSibling property to return the previous element of the specified element.

Use the children property to return any child element of a specified element.

The nextElementSibling property return a Node object representing the next sibling of an element, or null if there is no next sibling.




PreviousNext

Related