Web Wish 21: Has Slotted
Need to style your web-component differently depending on whether a slot has a slotted element?
Right now you would need to listen to the slotchange
event, and check if the slot has any assignedNodes
, and set a class to style the element.
const slots = this.shadowRoot.querySelectorAll('slot')
for (const slot of slots) {
slot.addEventListener('slotchange', () => {
slot.classList.toggle('has-slotted', slot.assignedNodes().length > 0)
})
}
slot:not(.has-slotted) {
display: none;
}
It would be awesome if it was possible to style the slot based on whether it has slotted content, without waiting for the javascript to run.
slot:not(:has-slotted) {
display: none;
}
There is an open issue for a :has-slotted
pseudo-class, and things have been moving fast.
The CSS Scoping spec is now updated with a :has-slotted
section,
and there are prototypes in Chrome and in Firefox.
I hope the CSSWG keep up the momentum, so that we might soon have a :has-slotted
pseudo-class,
and perhaps, in time, a functional :has-slotted()
pseudo-class.