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>
</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;
console.log(nextSibling)
const prevSibling = div.previousElementSibling;
console.log(prevSibling)
Then nextSibling
is the div with ID inner3
.
And prevSibling
is the div with ID inner1
.