Let’s say I have an element and I want to select the next matching sibling. Normally, in css I’d be able to write <some selector for this element> ~ <selector for sibling>
, but the sibling combinators (~
and +
) don’t seem to work when applied inside querySelector
with the :scope
pseudo-selector.
Here’s an example
<div id="container">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item active"></div>
<div class="item"></div>
<div class="item"></div>
</div>
document.addEventListener("DOMContentLoaded", () => {
const container = document.getElementById('container');
// this is my element that I have and I want to get the next .active
const item = container.querySelector('.item:nth-child(2)');
// this doesn't work
const nextActiveFromSibling = item.querySelector(':scope ~ .active');
console.log(`From sibling success: ${nextActiveFromSibling !== null}`);
// this works but requires me to know how to select the original item from the parent
const nextActiveFromParent = container.querySelector('.item:nth-child(2) ~ .active');
console.log(`From parent success: ${nextActiveFromParent !== null}`);
});
prints:
From sibling success: false
From parent success: true
Why doesn’t :scope ~ .active
work when applied to the selected item?