How to Returns the next element at the same node tree level in JavaScript ?
To return the next element at the same node tree level in JavaScript, there are multiple methods:
- Using the
nextSibling
property: ThenextSibling
property returns the next sibling node at the same level as the current node. We can use a loop to traverse through the siblings until we find the next element node.
Example:
const currentElement = document.getElementById("currentElement");
let nextElement = currentElement.nextSibling;
while (nextElement && nextElement.nodeType !== 1) {
nextElement = nextElement.nextSibling;
}
console.log(nextElement);
- Using the
nextElementSibling
property: ThenextElementSibling
property returns the next sibling element at the same level as the current element. We can simply use this property to get the next element.
Example:
const currentElement = document.getElementById("currentElement");
const nextElement = currentElement.nextElementSibling;
console.log(nextElement);
- Using the
querySelector
method: We can use thequerySelector
method to select the next element at the same level using a CSS selector.
Example:
const currentElement = document.getElementById("currentElement");
const nextElement = currentElement.parentNode.querySelector(":scope > *:not([hidden]):not(#currentElement)");
console.log(nextElement);
In this example, we first select the parent node of the current element using the parentNode
property. Then we use the querySelector
method to select the next element at the same level using the :scope
pseudo-class and the >
child combinator. We also exclude any hidden elements and the current element using the :not
pseudo-class and the #currentElement
selector.