[csswg-drafts] Proposal for custom matched sets of elements (#7679)

romainmenke has just created a new issue for https://github.com/w3c/csswg-drafts:

== Proposal for custom matched sets of elements ==
When looking at the API for [`Highlights`](https://css-tricks.com/css-custom-highlight-api-early-look/) I drew a parallel to a set of problems I often encounter.

1. Applying styles on elements for states that can only be determined through Javascript
   1. Element is 50% or more visible
   2. Page is scrolled
2. Creating polyfills for selectors
   1. `:focus-within`
   2. `:has()`
   3. ...

Both sets of problems require developers to take a detour with DOM manipulation.

The pattern is mostly the same for each case. We will create an event listener with the relevant API (scroll event listener, `IntersectionObserver`, ...) and then add a class or attribute on certain elements.

In CSS we would write styles for certain elements that have this class or attribute.

Changing the DOM is orthogonal to the intended result.
You want to make a known set of elements match certain CSS rules.

With the API for `Highlights` I was wondering if we could have something similar for matching elements.

```css
/* maybe has zero specificity? [0, 0, 0] */
:node-set(my-custom-set) {
 color: pink;
}
```

```js
const nodeSet = new NodeSet(); // Same API as `Set`

CSS.nodeSets.set('my-custom-set', nodeSet);

// Use any JS API to add or remove elements from the set.
nodeSet.add(document.getElementById('alpha'));
nodeSet.add(document.getElementById('beta'));
```

------

The main benefit of a feature like this would be the ability to leave the DOM as-is while still applying styles based on state.

I don't think this will be useful for every case where developers now add a class or attribute with Javascript.
I think it could be a more low level API that allows polyfills and frameworks to apply styles without touching the DOM.

_Changing the DOM can have unintended side effects and can cause performance issues._

_The names used in this proposal need work, but bike-shedding can happen later._

Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/7679 using your GitHub account


-- 
Sent via github-notify-ml as configured in https://github.com/w3c/github-notify-ml-config

Received on Friday, 2 September 2022 17:32:10 UTC