Sometimes, we want to select sibling nodes with JavaScript.
In this article, we’ll look at how to select sibling nodes with JavaScript.
How to select sibling nodes with JavaScript?
To select sibling nodes with JavaScript, we can use various properties of an element.
For instance, we write
const previousSibling = node.previousSibling;
const nextSibling = node.nextSibling;
to use the previousSibling to get the previous sibling node of node.
And we use the nextSibling to get the next sibling node of node.
These properties will return any type of nodes.
To return only element nodes, we write
const previousSibling = node.previousElementSibling;
const nextSibling = node.nextElementSibling;
to use the previousElementSibling to get the previous sibling element of node.
And we use the nextElementSibling to get the next sibling element of node.
Conclusion
To select sibling nodes with JavaScript, we can use various properties of an element.