Categories
JavaScript Answers

How to get next / previous element using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *