Explain Codes LogoExplain Codes Logo

Can I add a custom attribute to an HTML tag?

html
responsive-design
data-attributes
accessibility
Nikita BarsukovbyNikita Barsukov·Sep 7, 2024
TLDR

Indeed, HTML5 provides the ability to add custom attributes with the prefix data- . Here's a quick example:

<button data-action="save">Save</button>

You can retrieve these attributes in JavaScript via the .dataset property:

let action = document.querySelector('button').dataset.action; // 'save', not 'John Cena' because you can actually see this

Remember, using a data- prefix ensures compatibility and safeguards against potential clashing with future HTML attributes.

Diving deeper into the custom attribute ocean

Just because you CAN, doesn't mean you SHOULD

Custom attributes can be handy, but it's wise to use them sparingly and for non-obtrusive data. Overusing them may clutter your code and confuse assistive technologies like screen readers.

jQuery to the rescue

The jQuery data() function provides an accessible toolset for dealing with these custom attributes. It is cleaner and concise:

$('button').data('action', 'cancel'); // Set data-action to 'cancel', calm down Karen. let action = $('button').data('action'); // Retrieve the 'cancel', or the calm Karen.

But beware, jQuery may not always reflect direct manipulations of the data- attributes in the fetched data unless DOM manipulations are performed afterwards.

Crafting your DTD carefully

For the diligent coders wanting to validate custom attributes, you can amend your !DOCTYPE and create a custom Document Type Definition (DTD).

<!ATTLIST element-name custom-attribute CDATA #IMPLIED>

The above line declares optional custom attributes using the #IMPLIED keyword. The downsides? This approach is quite outdated and typically unnecessary with the robust flexibility of HTML5.

Mastering the art of custom attributes

Accessibility goes beyond custom attributes

It's crucial to prioritize accessibility while implementing data- attributes. Try to avoid utilizing them for styling or behavioral aspects as it may render the content less accessible to everyone.

World domination... I mean, cross-browser compatibility

Cross-browser compatibility is a significant aspect of web development. Carrying out testing in multiple browsers ensures a consistent user experience. And remember, a happy user is a loyal user.

Saying "YES" to HTML standards

Adhering to HTML validation standards is a must, especially when you're using custom attributes. Validate your HTML document with a reliable tool such as the W3C Markup Validation Service. It will give your code a thumbs up for being awesome (or help you make it so)!