If two page elements have the same parent, those elements are said to be siblings of each other. To target the siblings of a reference element where those siblings come after the reference element in the DOM, use the sibling selector (~) (which is also known as the sibling combinator and the next siblings selector):
reference ~ siblings
{
CSS declarations that get applied to the specified siblings
of reference
that come after reference
}W3C Specification: https://www.w3.org/TR/selectors-3/#general-sibling-combinators
document.querySelector('reference ~ sibling')
document.querySelectorAll('reference ~ sibling')
$('reference ~ siblings')
jQuery Documentation: https://api.jquery.com/next-siblings-selector/
All the examples present four div
elements that are siblings—that is, each is a child 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 all the elements with class .sibling-element
that are siblings of, and come after, the element with the class .reference-element
. This selector is used three times:
CSS:
In the CSS example, the selector’s targeted elements are styled with color: seagreen
.
JavaScript:
In the JavaScript example, the selector’s targeted elements are styled with style.fontVariant = 'small-caps'
.
jQuery:
In the jQuery example, a jQuery statement uses the selector to apply the sans-serif
generic font to the font-family
property.