Categories
JavaScript Answers

How to get the next / previous element using JavaScript?

Spread the love

To get the next / 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>

Then we write

const foo3 = document.getElementById("foo2").nextSibling;
const foo1 = document.getElementById("foo2").previousSibling;

to get the element with ID foo2 with getElementById.

We get its next sibling with nextSibling, which is the div with ID foo3.

And get its previous sibling with previousSibling, which is the div with ID foo1.

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 *