I have a custom HTML tag <fancy-foo>
that I would like to extend the functionality of. Some of the <fancy-foo>
elements would be extended using the pretty-bar
custom element, so that I can use them in my HTML as
<fancy-foo is="pretty-bar">
<!-- content -->
</fancy-foo>
so, I define classes FancyFoo
and PrettyBar
, define the fancy-foo
element and extend it using pretty-bar
, like so:
class FancyFoo extends HTMLElement {
constructor() {
super();
}
}
class PrettyBar extends FancyFoo {
constructor() {
super();
}
}
window.customElements.define('fancy-foo', FancyFoo);
window.customElements.define('pretty-bar', PrettyBar, {extends: 'fancy-foo'});
Sadly, Google Chrome spits out the error
Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': "fancy-foo" is a valid custom element name
That's an odd error. Strangely, it says "fancy-foo" is a valid custom element name; I know that, but why should that throw an error?
What's going on here?
And it doesn’t stop there. Instead of extending HTMLElement, Custom Elements can also extend other built-in HTML elements like <button>, <img> and <a> for example. Let’s say we want to create a lazy loading image that will not load until it’s scrolled into the viewport.
Two kinds of custom elements can be distinguished: Autonomous: to this group are related the “all-new” elements that extend the HTMLElement class. Customized built-in elements: these are the ones that extend built-in elements such as a customized button built on the HTMLButtonElement. We will start at discovering the autonomous custom elements.
In order to build a custom element, a javascript class is necessary to extend HTMLElement and define the class with a tag name. A fundamental version of a custom element: Despite the fact that this example isn’t advanced, it allows being used as a starting block.
customElements.define('word-count', WordCount, { extends: 'p' }); The element is called word-count, its class object is WordCount, and it extends the <p> element. A custom element's class object is written using standard ES 2015 class syntax.
You cannot extend Custom Elements that way (with {extends: '...'}
). You can only extend buit-in (= standard) HTML elements.
If you want to design PrettyBar
as an extension of FancyFoo
, you'll need to define it as an autonomous custom element:
class PrettyBar extends FancyFoo {...}
window.customElements.define('pretty-bar', PrettyBar)
Same thing for the HTML tag:
<pretty-bar></pretty-bar>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With