DEV Community

Jochem Stoel
Jochem Stoel

Posted on

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

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



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


Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

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



<x-void />
<br />


Enter fullscreen mode Exit fullscreen mode

Failed

Thoughts?

Top comments (2)

Collapse
 
denmch profile image
Den McHenry • Edited

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.

Collapse
 
nektro profile image
Meghan (she/her)

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.