Question

  1. According to many recent HTML specs, when we are using custom attributes (meaning any attributes not defined in the spec), we should prefix them with data-. However, I see no reason to have to do this (unless you require perfectly valid HTML, obviously). Pretty much all current browsers correctly ignore custom attributes, meaning no conflicts except with identically-named attributes from others' code, and we can ignore even this with custom prefixes or something similar (as suggested on the AngularJS directive page). What, if any, other benefits are there? This question has been asked before, at least twice, but both are pretty old.

  2. I forget where I read it, but some guide said custom HTML tags need dashes, and single-word tags aren't valid. First of all, why? Second, should we do this, and why (besides being valid)? Would there be any problem with underscores or camelCase, etc.? Also, conflicts with existing elements shouldn't be a problem, if, like with data attributes, you prefix or suffix them, etc. See the Angular directive page again.

I'm sure all these questions have been asked before, but I'm combining them into one. Is that a good idea (quick, someone ask on Meta)?

Was it helpful?

Solution

The data-* attributes have two advantages:

  1. It is a convention meaning other programmers will understand quickly that it is a custom attribute.
  2. You get a DOM Javascript API for free: HTMLElement.dataset. If you use jQuery, it leverages this to populates the keys and values you find with .data().

The reason for the - in custom element names is for two basic reasons:

  1. It is a quick way for the HTML parser to know it is a custom element instead of a standard element.
  2. You don't run into the issue of a new standard element being added with the same name which would cause conflict if you register a custom Javascript prototype for the DOM element.

Should you use your own custom element name? Right now it is so new that don't expect it to be fully supported. Let's say it does work. You have to balance the issue of the extra complexity with the benefit. If you can get away with a classname, then use a classname. But if you need a whole new element with a custom Javascript DOM prototype for the element, then you may have a valid usage of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top