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:
- 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:
- element1 and element2 are element selector
Example:
div+div{
color: red
}
<div>Hello</div>
<div>The red sibling</div>
Next in Javascript
- With a querySelector
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>