I want to be able to listen to CSS selector state changes on elements, similarly to matchMedia

Submitted by Guylian Cox

This idea is currently being discussed.

I want to be able to listen for changes in whether a CSS selector matches a given element, in much the same way that matchMedia lets me react to media query changes.

The Element.matches(selector) method lets me test whether an element matches a CSS selector at a single point in time, but it gives me no way to be notified when the match state changes. For instance, I cannot be told when an input transitions into or out of :placeholder-shown, :user-invalid, or :focus-visible without polling or attaching workaround event listeners. This limitation is particularly painful in scenarios where:

The API I am imagining is analogous to matchMedia:

const observer = element.matchSelector(':placeholder-shown');
observer.addEventListener('change', (event) => {
console.log('placeholder shown:', event.matches);
});

A more ambitious alternative — which would cover all of the above and more — is a CSS.observe() primitive that notifies script whenever any element's match state changes for an observed selector:

CSS.observe('input:placeholder-shown', (selector, records) => {
// records: [{ target: inputEl, matches: true/false }]
});

Either form would dramatically reduce the need for polling loops, multiple MutationObservers, or fragile event-handler combinations just to react to CSS pseudo-class state changes.

Tagged
JavaScript CSS Dom
Votes
0
What are votes for and how are they tallied?