HTML - DOM Element nextElementSibling Property



The HTML DOM Element nextElementSibling property is used to retrieve the immediate next element node in the sequence of a particular element. The immediate next node will be the next sibling of the given element.

Note: It will not consider nodes that are not elements, such as text or comment nodes. If no next sibling is there for the given element, it will return null.

Syntax

Following is the syntax of the HTML DOM Element nextElementSibling() property −

element.nextElementSibling

Parameters

Since this is a property, it will not accept any parameter.

Return Value

This property returns a node that contains the next sibling of a given element. It returns 'null' if there is no next sibling.

Example 1: Accessing the Next Sibling Element

The following example demonstrates the usage of the HTML DOM Element nextElementSibling() property. It retrieves the next sibling node of the <div> element −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM Element nextElementSibling</title>
<style>
   .highlight {
      color: red;
   }
</style>
</head>
<body>
<h3>HTML DOM Element nextElementSibling Property</h3>
<p>Below are the contents of the parent element:</p>
<div id="parent">
   <p>First paragraph</p>
   <div>Second div</div>
   <span>Span element</span>
   <p>Last paragraph</p>
</div>
<p id="output"></p>
<script>
   const firstParagraph = document.querySelector('#parent p');  
   const nextElement = firstParagraph.nextElementSibling;
   const outputDiv = document.getElementById('output');
   outputDiv.innerHTML = `Next sibling element found:
   <span class="highlight">${nextElement.textContent}</span>`;        
</script>
</body>
</html>        

The above program displays the next sibling of the "div" element.

Example 2: Handling No Next Sibling

Here is another example of the HTML DOM Element nextElementSibling() to handle cases where there is no next sibling element for a given element −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM Element nextElementSibling</title>
</head>
<body>
<h3>HTML DOM Element nextElementSibling Property</h3>
<p>Below are the contents of the parent element:</p>
<div id="parent">
<p>First paragraph</p>
</div> 
<div id="output"></div>
<script>
   // Accessing Sibling when no next sibling exists
   const fp = document.querySelector('#parent p');
   const nextEle = fp.nextElementSibling;
   if (nextEle) {
       document.getElementById('output').textContent = 
	   `Next sibling element found: ${nextEle.textContent}`;
   } else {
       document.getElementById('output').textContent = 
	   'No next sibling element found.';
   }
</script>
</body>
</html>       

The above program handles and displays the "No next sibling element found" if no next sibling is there for the given element.

Supported Browsers

Property Chrome Edge Firefox Safari Opera
nextElementSibling Yes Yes Yes Yes Yes
html_dom.htm
Advertisements