JavaScript Answers

How to Select Sibling DOM Nodes with JavaScript?

Spread the love

We can select siblings nodes with the nextElementSibling and the previousElementSibling properties.

For instance, if we have the following HTML:

`<div id="outer">
  <div id="inner1"></div>
  <div id="inner2"></div>
  <div id="inner3"></div>
  <div id="inner4"></div>

Then we can select the next and previous siblings of the div with ID inner2 by writing:

const div = document.querySelector('#inner2')
const nextSibling = div.nextElementSibling;
const prevSibling = div.previousElementSibling;

Then nextSibling is the div with ID inner3 .

And prevSibling is the div with ID inner1 .

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 *