Two page elements — call them element A and element B — are said to be siblings of each other if they share the same parent element. In particular, if element B comes immediately after element A in the DOM, then element B is said to be adjacent to element A. To target the sibling of a reference element where that sibling occurs immediately after the reference element in the DOM, use the adjacent sibling selector (+) (which is also known as the adjacent sibling combinator and the next sibling selector):
reference + sibling
{
CSS declarations that get applied to the specified sibling
of reference
when it comes immediately after reference
}W3C Specification: https://www.w3.org/TR/selectors-3/#adjacent-sibling-combinators
document.querySelector('reference + sibling')
$('reference + sibling')
jQuery Documentation: https://api.jquery.com/next-adjacent-selector/
Each example presents three div
elements that are siblings: child elements of the parent section
element. The second div
(the one with class="reference-element"
) is the reference element. The examples use the sibling selector .reference-element + .sibling-element
to target the element with class .sibling-element
that is the adjacent sibling of the element with the class .reference-element
. This selector is used three times:
CSS:
In the CSS example, the selector’s targeted element is styled with background-color: goldenrod
.
JavaScript:
In the JavaScript example, the selector’s targeted element is styled with style.color = 'orange'
.
jQuery:
In the jQuery example, a jQuery statement uses the selector to apply the value 2rem
to the font-size
property.