Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom HTML element extending another custom element

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?

like image 477
vrugtehagel Avatar asked Aug 02 '19 18:08

vrugtehagel


People also ask

Can custom elements extend htmlelement?

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.

What are the types of custom elements in HTML?

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.

How to build a custom element using JavaScript?

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.

How do you define a custom element with a class object?

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.


1 Answers

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>
like image 111
Supersharp Avatar answered Oct 14 '22 05:10

Supersharp