Sometimes, we want to get next / previous element using JavaScript.
In this article, we’ll look at how to get next / previous element using JavaScript.
How to get next / previous element using JavaScript?
To get next / previous element using JavaScript, we can 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
document.getElementById("foo2").nextSibling;
document.getElementById("foo2").previousSibling;
to get the next and previous sibling of the div with ID foo2
with nextSibling
and previousSibling
.
Conclusion
To get next / previous element using JavaScript, we can use the nextSibling
and previousSibling
properties.