Sometimes, we want to get the next or previous element using JavaScript.
In this article, we’ll look at how to get the next or previous element using JavaScript.
How to get the next or previous element using JavaScript?
To get the next or previous element using JavaScript, we use the nextSibling
and previousSibling
properties.
For instance, we write
<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>
to add 3 divs.
Then we write
const foo3 = document.getElementById("foo2").nextSibling;
const foo1 = document.getElementById("foo2").previousSibling;
to get the div with ID foo2
with getElementById
.
We get its next sibling with the nextSibling
property.
And we get its next sibling with the previousSibling
property.
Conclusion
To get the next or previous element using JavaScript, we use the nextSibling
and previousSibling
properties.