Selector API - Sibling selector (adjacency - before after)

Chrome Devtool Selector

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 sibling with the wildcard (+)
  • following sibling with the wildcard (~)

Next

A Adjacent / Next-sibling selector matches if:

  • E1 and E2 share the same parent in the document tree (sibling)
  • and E1 immediately precedes E2, ignoring non-element nodes (such as text nodes and comments).

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>
  • With the tree nextElementSibling attribute.
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:

  • The element 1 must be above the element 2
  • The element 2 does not need to be the next sibling but in another position in the list

Example:

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





Discover More
DOM - Sibling Manipulation

This page is Sibling manipulation in the DOM can insert at this positions: See Sibling selector insertAdjacentElement...
Chrome Devtool Selector
Selector API

API A selector is a boolean expression (known also as predicate) that match against elements in a DOM tree in order to select one or several node. This API was known before as the CSS and was renamed...



Share this page:
Follow us:
Task Runner