loading...

[HTML5/JS] Define a custom self closing (void) HTML element like BR and IMG

jochemstoel profile image Jochem Stoel ・1 min read

I am unable to (re)produce a self closing element. Is it impossible?

<img />
<br />
<link />
<meta />

Self closing HTML elements do not require or support a closing tag.

Modern browsers support custom element tags and behavior using document.registerElement.

Try to extend already void HTML element fails.

class HTMLVoidElement extends HTMLBRElement {
}

document.registerElement('x-void', HTMLVoidElement)
document.createElement('x-void') // returns <x-void></x-void>

It makes no difference if the element is in the document HTML and not created programmatically.

<x-void />
<br />

Failed

Thoughts?

Posted on Aug 9 '18 by:

jochemstoel profile

Jochem Stoel

@jochemstoel

Pellentesque nec neque ex. Aliquam at quam vitae lacus convallis pulvinar. Mauris vitae ullamcorper lacus. Cras nisi dui, faucibus non dolor quis, volutpat euismod massa. Donec et pulvinar erat.

Discussion

markdown guide
 

The W3C has ruled this out as it would require rewriting the HTML parser:

There's no interest in changing the HTML parser for void elements. The bar for changes is too high and the ergonomic benefit is too low.

 

It seems the W3C had decided not to allow this, but if they ever changed their mind, it would be added to customElements.define since Custom Elements is at v1 now and document.registerElement is from v0 and will be being deprecated soon.