If I forget to register a custom element, I can still:
- customize the unregistered element using CSS
- attach events to the unregistered element using JS
For example:
// REGISTER <my-custom-element-1>
class MyRegisteredCustomElement1 extends HTMLElement {
constructor() {
super();
}
};
customElements.define('my-custom-element-1', MyRegisteredCustomElement1);
// ATTACH EVENT LISTENERS TO BOTH CUSTOM ELEMENTS
const myCustomElement1 = document.getElementsByTagName('my-custom-element-1')[0];
const myCustomElement2 = document.getElementsByTagName('my-custom-element-2')[0];
const customElementAlert = (e) => {
switch (e.target.nodeName.toLowerCase()) {
case ('my-custom-element-1') : console.log('I\'m a registered custom element and I can be scripted and styled.'); break;
case ('my-custom-element-2') : console.log('I\'m an unregistered custom element. Nevertheless, I can be scripted and styled TOO.'); break;
}
}
myCustomElement1.addEventListener('click', customElementAlert, false);
myCustomElement2.addEventListener('click', customElementAlert, false);
:not(:defined) {
border: 1px dashed rgb(0, 0, 0);
}
my-custom-element-1,
my-custom-element-2 {
float: left;
display: inline-block;
width: 100px;
height: 100px;
margin-right: 12px;
padding: 6px;
text-align: center;
font-weight: bold;
cursor: pointer;
}
my-custom-element-1 {
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
my-custom-element-1::after {
content: 'I\'m a registered custom element.\A CLICK ME';
}
my-custom-element-2 {
background-color: rgb(255, 255, 0);
}
my-custom-element-2::after {
content: 'I\'m an unregistered custom element.\A CLICK ME';
}
<my-custom-element-1></my-custom-element-1>
<my-custom-element-2></my-custom-element-2>
Despite being able to style and script unregistered elements, what specific advantages does registering a custom element provide?