Table of Contents

Selector API - Sibling selector (adjacency - before after)

About

selection of sibling (ie node that share the same parent in the document tree)

If you want to add a sibling in the DOM, see DOM sibling manipulation

Syntax

There is two sibling selector selection:

Next

A Adjacent / Next-sibling selector matches if:

Next in Css

element1 + element2

where:

Example:

div+div{
  color: red
}
<div>Hello</div>
<div>The red sibling</div>

Next in Javascript

let nextSibling = document.querySelector("#hello + div");
nextSibling.style.setProperty('color', 'red')
<div id="hello">Hello</div>
<div>The red sibling</div>
let helloElement = document.getElementById("hello");
let nextSibling = helloElement.nextElementSibling;
nextSibling.style.setProperty('color', 'red')
<div id="hello">Hello</div>
<div>The red sibling</div>

Following

element1 ~ element2

where:

Example:

div~p{
  color: red
}
<div>Hello</div>
<div>World</div>
<p>The red sibling</p>