Skip to content Skip to sidebar Skip to footer

Web Components : Extending Native Elements

I'm trying to create a web component that extends the div element and I found this other Stack Overflow question about how to extend native elements (a button in this case). Howeve

Solution 1:

AFAIK

There are 2 types of Custom Elements MDN: Using Custom Elements

  • Autonomous Custom Elements
  • Customized Built-In Elements Polyfill required for Safari because Apple... well.. is Apple..and refuse to implement Customized Elements

One registry to rule them all

There is only one registry so your Customized element is registered as fancy-button; But can NOT* be used with Autonomous notation:<fancy-button></fancy-button/>

* Firefox DOES allow a mix of both notations BUT only if define() is used AFTER element usage


From docs section: Extending Native HTML Elements:

https://developers.google.com/web/fundamentals/web-components/customelements#extendhtml

Consumers of a customized built-in element can use it in several ways. They can declare it by adding the is="" attribute on the native tag:

<!-- This <button> is a fancy button. --><buttonis="fancy-button"disabled>Fancy button!</button>

create an instance in JavaScript:

// Custom elements overload createElement() to support the is="" attribute.let button = document.createElement('button', {is: 'fancy-button'});
    button.textContent = 'Fancy button!';
    button.disabled = true;

    // have to do this yourself!! IF you want to use it as a selector
    button.setAttribute("is","fancy-button");

    document.body.appendChild(button);

or use the new operator:

let button = new FancyButton();
    button.textContent = 'Fancy button!';
    button.disabled = true;

Conclusion

There are 2 types of Custom Elements, you can't mix

You either go for:

  • Autonomous Custom Element: <fancy-button></fancy-button>

or

  • Customized Built-In Element <button is=fancy-button></button>

for Customized Built-In Elements

document.createElement('fancy-button') instanceof HTMLButtonElement

returns false

and

<fancy-button>lightDOM</fancy-button>

document.querySelector('fancy-button')

returns the element (if in the DOM), but the element is processed as an undefined Element displaying the lightDOM contents


Example using both types of Custom Elements

In https://cardmeister.github.io I used both:

<card-t rank=queen suit=hearts></card-t>

<img is=queen-of-hearts/>

Thus I could not do:

<queen-of-hearts></queen-of-hearts>

The latter has little value, with IMG the is attribute can be used for CSS targetting. CSS Selector for a partial CustomElement nodename

Post a Comment for "Web Components : Extending Native Elements"