Don’t Misuse REL as a Custom Attribute
There are often situations when it’s useful to add custom data to an HTML tag. In my recent series How to Build an Auto-Expanding Textarea jQuery Plugin, I assigned a name of “expand” to a
Custom data may not be displayed by the browser, but is convenient as a programmatic hook. Most developers are aware that custom attributes do not exist in HTML4…
<!-- this is not valid --> <div myattribute="mydata"></div>
Browsers will not normally complain, but you cannot be absolutely certain how the attribute will be handled. Some will add it to the DOM and some may ignore it completely. Your page will also fail validation which makes it more difficult to spot real errors.
Unfortunately, there is common misconception that the ‘rel’ attribute is unused and can be adopted in any situation that requires custom data. Don’t make that assumption. In HTML4.01 and XHTML1.0, ‘rel’ can only be used as an attribute for
link tags. Your code will be invalid if you assign it elsewhere.
In addition, ‘rel’ describes the relationship between the current document and the document or anchor specified in the href attribute. That relationship can be one or more of the following types: alternate, stylesheet, start, next, prev, contents, index, glossary, copyright, chapter, section, subsection, appendix, help, and bookmark. At best, your custom data will be ignored. At worst, a future revision of HTML might define your data as a specified link type and handle your attribute in an undesired way.
The HTML5 specification is slightly different. It also permits rel attributes on
area tags and defines the link types: alternate, archives, author, bookmark, external, feed, first, help, icon, index, last, license, next, nofollow, noreferrer, pingback, prefetch, prev, search, stylesheet, sidebar, tag, and up.
However, HTML5 also offers us the custom data attribute which is any name starting with the string “data-“, e.g.
<!-- HTML5 custom data attribute --> <span data-speed-mps="186282">speed of light</span>
Unfortunately, the HTML5 specification is incomplete and browser support is patchy at best.
Alternatively, use ‘class’ if an appropriate attribute is not available. Most HTML elements support the class attribute and multiple names can be separated by white space characters.