Why Should I Prepend My Custom Attributes with "Data-"

Why should I prepend my custom attributes with data- ?

There are several benefit for keeping custom attributes prefixed with data-*.

  1. It guarantees there will not be any clashes with extensions to HTML in future editions. This is a problem that has been encountered to some degree already with some of the new attributes introduced in HTML5, where existing sites were using attributes with the same name and expecting different and incompatible, custom behaviour. (e.g. the required attribute on input elements is known to have had some clashes on some popular websites in the past)

  2. There is a convenient DOM API, HTMLElement.dataset, for accessing these attributes from scripts. It is now supported in most browsers.

  3. They provide a clear indication of which attributes are custom attributes, and which ones are standardised attributes. This not only helps validators by allowing them to permit any attribute with data-* while still performing useful error checking for other attributes (e.g. to catch typos), it also helps make this aspect of the source code clearer to those reading it, including people who may work on a website after the original author.


Is there any reason I should stick strictly to data- attributes for custom attributes?

Yes.

MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

  1. Clean "namespace": You don't need to restrict yourself about which attributes you can use. data-bgcolor is safe to use, bgcolor is not.

  2. Semantics: The way data and non-data attributes are accessed is different. Usually, attributes will be retrieved using el.getAttribute("value"), while data attributes will be access with el.dataset.value. This is no confusion about what the attribute does (is it visual or not).

  3. It's standard: HTML5 declares a specific set of valid attributes. Going against standards should generally be avoided.


Is it good practice to create custom HTML attributes for custom elements?

I have asked a similar question more than 3 years ago.

You're free to choose almost any attribute name you like, except the universal attributes ( e.g. id, class, title). In some cases even re-using attribute names that exist on some elements (like e.g. value, disabled, etc.) makes total sense so component consumers can work with your elements as though they were existing HTML elements.

Remember this freedom only applies when using autonomous custom elements (<foo-bar>), not when extending built-ins (<div is="foo-bar">)!

As to your second question, it's also totally okay to define/add properties in the constructor, but recent additions to the ES standard have added public and private class fields:

class InputFieldElement extends HTMLElement {
customProp = {data: 123}; // public class field
#abc = "Hello"; // only accessible from within this class via this.#abc
}

Except the private member, this class does exactly the same your class did, effectively saving you the need for a constructor. Please note that this is not yet available when assigning values to private or public class fields, meaning you cannot setup computed properties this way.

Regarding your specific question asking for type, having that attribute usually is an indicator of bad class design (which is true for HTMLInputElement e.g., resulting in text inputs with a use- and meaningless checked property, and checkboxes that have a readOnly property (which won't do anything either)), but cannot be changed any more due to web compat.

Naming rules for HTML5 custom data attribute(data-)

Straight from the spec:

3.2.3.9 Embedding custom non-visible data with the data-* attributes


A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters.

(emphasis added)


What does XML-compatible mean?

Attribute names are said to be XML-compatible if they match the Name production defined in XML and they contain no U+003A COLON characters (:).

What is the Name production rule?

[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]

[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]

[5] Name ::= NameStartChar (NameChar)*

Add custom attribute to HTML tags

Hopefully below code will be helpful for you.

<div id="navigation">
<ul>
<li customerId="1"></li>
<li customerId="2"></li>
<li customerId="3"></li>
</ul>
</div>
var x = document.getElementById('navigation');
if (!x) return;
var liCollections = x.getElementsByTagName('li');
for (var i=0;i<liCollections.length;i++)
alert(liCollections[i].getAttribute('customerid', 0));

It's clear enough, and you can understand it easily.

Why should I use data- in my attributes or dashes in my tags?

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.

Not able to get custom attribute data from Autodesk BIM360 for data management API

To get custom attributes of the document in BIM360, you will need to use another endpoint (Version:Batch:Get). This blog tells more.
https://forge.autodesk.com/blog/custom-attributes-apis-bim-360-document-are-now-public-beta

While please note, since March 23, 2021, in the newly created project, custom attributes definitions are created in project level (previously, in folder level), although you could still use the endpoint above to access the custom attributes, there is a gap that no endpoint yet to get definitions of project level. This blog tells more:
https://forge.autodesk.com/blog/custom-attributes-projects-created-and-after-march-23-2021

jQuery and SVG with custom attributes in Chrome

The data attribute name must be at least one character long and must
be prefixed with 'data-'. It should not contain any uppercase letters.

Try this -

<rect id='r' width="75" data-value="someValue">d</rect> 

$('rect[data-value]'); // select element with data-value attribute

$('rect').data('value'); // read attribute value

jsFiddle working demo



Related Topics



Leave a reply



Submit