3 ms·
Short answer: No. There is no guarantee that a future HTML spec will include a standard element <red> which will affect yours. For your element to be a legal cu
by runarberg 5y ago
Short answer: No. There is no guarantee that a future HTML spec will include a standard element <red> which will affect yours. For your element to be a legal custom element it must include a hyphen (e.g. <my-red>).
Longer answer: What you did here is a simple CSS selector using a tag matcher. Each tag with the name "red" will be matched and styles applied. If you want some custom script applied when this kind of element is created, attached, destroyed, etc. you must create a class for it and register it to the custom element registry[1]:
window.customElements.define(
"my-red",
class extends HTMLElement {
// ...
},
)
Now you have a custom element. But when people normally speak of web components they are talking about scoped elements, which means styles and idrefs are encapsulated. For that you must attach a shadow DOM[2] to your element:
class MyRed extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow();
const style = document.createElement("style");
const slot = document.createElement("slot");
style.textContent = ":host { color: red; }"
shadowRoot.append(style, slot);
}
}
1: https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry https://developer.mozilla.org/en-US/docs/Web/API/CustomEleme...
2: https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow https://developer.mozilla.org/en-US/docs/Web/API/Element/att...
- ______- 5y agoThanks for clarifying