3

If I have this HTML:

<div class="elem">
   <div class="child"></div>
</div>
<div class="sibling">
</div>

and the JS

let elem = document.querySelector('.elem');

Using elem.querySelector(":scope ~ div") does not return anything even though there are div siblings of elem.

Using elem.querySelector(":scope > div") returns an element because also there are are div children of elem.

How could I select the current sibling of elem having the js object for elem already selected in a js variable (let elem = document.querySelector('.elem'))?

  • Please post your HTML or DOM structure. – Dai Jan 06 '21 at 12:38
  • 2
    Note that `~` actually selects **subsequent** siblings, not **previous** siblings. CSS is strictly "forward-only". – Dai Jan 06 '21 at 12:39
  • 1
    and how could i select the sibling of current element, elem, using querySelector ? – Andrei Diaconescu Jan 06 '21 at 12:44
  • The reference element pseudo-class `:scope` seems to be incompatible with the next-sibling combinator `+` or with the subsequent-sibling combinator `~`. I have no answer to this about why. – Simon Jul 06 '22 at 13:26
  • 2
    **Answer**: The reference element pseudo-class `:scope` define a scoping-root and thus any matched element "must be within the scope". A sibling is not in the scope (aka: descendant) of the `:scope`. This is why it does not apply. https://drafts.csswg.org/selectors/#scoping-root https://drafts.csswg.org/selectors/#the-scope-pseudo – Simon Jul 06 '22 at 13:34

0 Answers0