Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What repercussions do I get by using an undefined HTML element?

In an effort to write more expressive HTML, I feel custom HTML elements are a good way for any webapp or document I may write to have good meaning gleamed from the tag name itself without the use of comments.

It appears I can define a custom HTML element with:

document.registerElement("x-el");

However it also appears that I can use a custom element before defining it:

<body>
    <x-salamander>abc</x-salamander>
</body>

Or even:

<salamander>abc</salamander>

I suppose this is invalid HTML, however both Firefox and Chromium proceed to display the element without any problems or console warnings.

I can even execute the following with no complaints from the browser:

document.getElementsByTagName("salamander")[0]

Using this tag name as a selector in CSS also works fine. So, what problems might I face if I use undeclared elements in this way?

like image 328
Marco Scannadinari Avatar asked Mar 19 '23 10:03

Marco Scannadinari


1 Answers

The problem with what you're trying to do is not that we can tell you it will break in some expected ways. It's that when you deviate from standards in this way, no one knows what to expect. It is, by definition, undefined, and the behavior of browsers that see it is also undefined.

That said, it might work great! Here's the things to keep in mind:

  1. The HTMLUnknownElement interface is what you're invoking to make this work in a supported way - as far as I can tell in 5 minutes of searching, it was introduced in the HTML5 spec, so in HTML5 browsers that use it appropriately, this is no longer an undefined scenario. This is where registerElement comes into play, which can take an HTMLUnknownElement and make it known.
  2. Browsers are typically very good at coping with unexpected markup... but it won't always result in great things (see: quirks mode).
  3. Not all browsers are created equal. Chrome, Firefox, Safari, Opera, even IE will likely have some reliable way to handle these elements reliably (even pre-HTML5)... but I have no idea what a screen reader (Lynx) or various other esoteric, outdated, niche or even future browsers will do with it.
  4. Everyone has said the same thing, but it's worth noting: you will fail validation. It's OK to have validation errors on your page so long as you know what they are and why they are there, and this would qualify, but you'd better have a good reason.

Browsers have a long history of taking whatever you give them and trying to do something reasonable with it, so you're likely to be OK, and if you are interested in primarily targeting HTML5 browsers, then you're very likely to be OK. As with everything HTML related, the only universal advice is to test your target demographic.

like image 108
Jason Avatar answered Apr 06 '23 15:04

Jason