🎨 CSS: Fix a :has() Selector Missing Matches After a DOM Swap
:has() is a relational pseudo-class meant to be evaluated live against the current DOM tree, so its matches are supposed to update automatically whenever the DOM changes underneath it. A framework that swaps content via a wholesale innerHTML replacement, or a virtual-DOM diff that replaces a parent element entirely rather than patching its existing children in place, can detach and reattach a subtree in a way that doesn’t fire the style recalculation some engines expect before :has() is re-evaluated against the new children, so a style depending on it matching a freshly-inserted descendant doesn’t apply until some unrelated layout or paint event forces a recalculation.
🔎 The Problem
/* intended: highlight any .card that now contains a .badge--new,
inserted dynamically after an AJAX update replaces the card's
inner HTML wholesale instead of patching it in place */
.card:has(.badge--new) {
border-color: #f59e0b;
}
/* After element.innerHTML = newCardHtml, the .badge--new span
IS in the DOM, but the border doesn't apply until the user
hovers, resizes, or triggers any other unrelated recalc */
✅ Fix: Patch Precisely, or Force the Recalculation
- Prefer patching only the specific child that changed, with replaceChild or a templating library’s keyed diff, over wholesale innerHTML replacement of a parent, since a full subtree replacement is most likely to desync the relational match’s usual live-update timing.
- If a wholesale replacement is unavoidable, force a style recalculation immediately after the swap by reading a layout property like offsetHeight on the changed element, which reliably triggers a re-evaluation of :has() against the new subtree.
- Test the exact swap mechanism your framework actually uses, innerHTML versus appendChild versus a virtual-DOM patch, in each target browser engine, since this timing gap is engine- and swap-method-dependent rather than a documented, consistent rule.
🚨 Why This Is Dangerous
- A :has()-based style that silently fails to apply only after a dynamic DOM update, never on initial page load, is exactly the kind of bug that passes every static visual review and only shows up for users who trigger the live update path.
A relational selector that matches the DOM perfectly on paper can still miss the moment that DOM actually changed underneath it.





