Chumpocomon
Chumpocomon

Reputation: 733

How to define an empty custom HTML tag?

I know we can create custom tags directly like this:

<material-button>Cancel</material-button>

However, I would like to use an empty tag without creating a custom element (web component). Is it possible?

<icon-star>

Upvotes: 3

Views: 984

Answers (1)

Supersharp
Supersharp

Reputation: 31219

You may use <icon-star></icon-star> only.

You cannot use <icon-star> or <icon-star/> because it will be interpreted as an opening tag, and all content after will be interpreted as children nodes.

It's due to the way the custom elements are initialized: as unknowned element, so the parser cannot know if they are empty (atomic) or not. Only standard HTML elements can have that property (<img>, <br>) because they are already known when they are parsed.

customElements.define( 'icon-star', class extends HTMLElement {
  connectedCallback() {
    this.innerHTML = '*'
  }
} )
OK: <icon-star></icon-star>
Fail: <icon-star/> Hello
Fail: <icon-star/>

So actually you can use the open-only <icon-star> syntax for the last element of the page :-o

Upvotes: 4

Related Questions