HTML Element .nextElementSibling / previousElementSibling Since: DOM Level 1(1998)
A property for accessing sibling elements (adjacent elements that share the same parent) of an HTML element. You can navigate to the next or previous sibling element.
Syntax
// Get the next sibling element. var next = element.nextElementSibling; // Get the previous sibling element. var prev = element.previousElementSibling;
Property List
| Property | Description |
|---|---|
| nextElementSibling | Returns the next sibling element (HTML element). Returns null if no next sibling element exists. |
| previousElementSibling | Returns the previous sibling element (HTML element). Returns null if no previous sibling element exists. |
| nextSibling | Returns the next sibling node. This includes text nodes and comment nodes. |
| previousSibling | Returns the previous sibling node. This includes text nodes and comment nodes. |
Sample Code
<ul id="list"> <li id="item1">Item 1</li> <li id="item2">Item 2</li> <li id="item3">Item 3</li> </ul>
var item2 = document.querySelector("#item2");
// Get the next sibling element.
console.log(item2.nextElementSibling.textContent); // Outputs "Item 3".
// Get the previous sibling element.
console.log(item2.previousElementSibling.textContent); // Outputs "Item 1".
// The first element has no previous sibling.
var item1 = document.querySelector("#item1");
console.log(item1.previousElementSibling); // Returns null.
// The last element has no next sibling.
var item3 = document.querySelector("#item3");
console.log(item3.nextElementSibling); // Returns null.
// nextSibling may return a text node.
console.log(item1.nextSibling); // Returns a text node containing the newline and whitespace.
Overview
element.nextElementSibling and element.previousElementSibling are properties that navigate to adjacent elements among siblings that share the same parent element. nextSibling and previousSibling can return text nodes and comment nodes, whereas nextElementSibling and previousElementSibling return only HTML elements, making them the safer choice for typical DOM manipulation.
Combining these properties with element.parentNode and element.children lets you move freely through the DOM tree. For example, you can use them to build an accordion menu that toggles the visibility of the element following a clicked item.
To search for an ancestor element instead of a sibling, use element.closest(). To search among descendants, use element.querySelector().
Browser Compatibility
1 or earlier ×
2.5 or earlier ×
3.1 or earlier ×
8 or earlier ×
9 or earlier ×
Android Browser
37+ ○
4 or earlier ×
Chrome Android
36+ ○
17 or earlier ×
Firefox Android
79+ ○
3 or earlier ×If you find any errors or copyright issues, please contact us.