- Using Custom Attributes in HTML5
- Create Your HTML5 Document
- Create an Element
- Add a Test Button
- Get the Attribute
- Get the Dataset
- Other Methods and Functions
- Conclusion
- Element: setAttribute() method
- Syntax
- Parameters
- Return value
- Exceptions
- Examples
- HTML
- JavaScript
- Specifications
- Browser compatibility
- Gecko notes
- Found a content problem with this page?
Using Custom Attributes in HTML5
Custom attributes are among the most significant additions for HTML5, and can play a major role in semantic Web development. In this tutorial we’ll go through a practical example of creating and accessing HTML5 custom data attributes, including the necessary JavaScript functions.
It was possible before HTML5 to add your own attributes to HTML elements and access them using JavaScript, but if you’ve ever tried it you’ll know you can forget about getting your markup to validate. HTML5 provides the ability to create and use your own element attributes within valid pages.
Create Your HTML5 Document
If you don’t already have one you want to use, copy the following outline into an HTML file:
We will place our elements with custom attributes in the body and the JavaScript functions for accessing them in the head section script area.
Create an Element
Let’s add an element with some simple content and a custom attribute as well as an ID so that we can identify it in JavaScript for demonstration:
As you can see, the custom attribute has the form: “data-*” with a name or names of your choice after the “data-” section. This is the only valid way to use custom attributes in HTML5, so make sure you start your elements this way if you need your pages to validate.
Of course the details of your own projects will dictate whether custom attributes are useful to you, as well as how to go about naming them. This example could be for a retail site with different product categories. The custom attributes allow you to treat elements in particular ways within the JavaScript code for the page, for example when using animated display functions. It’s really only advisable to use custom attributes if there is no standard HTML attribute available to do what you need.
Add a Test Button
Your own JavaScript functions will execute on events within your pages, but to demonstrate add the following button to your page:
The button passes the element ID as parameter, so that the JavaScript function can refer to it and access its custom attribute.
Get the Attribute
The most common way to access attributes in JavaScript is using “getAttributes” which is what we’ll do first. Add the following function in the script section of your page head:
function getElementAttribute(elemID)
We alert the attribute value for demonstration, but your own scripts can do whatever you need with it.
Get the Dataset
As an alternative to the DOM “getAttributes” method, you can use the element dataset. This can be more efficient, particularly in cases where your code is iterating through a variety of attributes. However, browser support for dataset is still very low, so do bear this in mind. This code carries out the same process as the line commented out from the previous approach:
//var theAttribute = theElement.getAttribute('data-product-category'); var theAttribute = theElement.dataset.productCategory;
With dataset you remove the “data-” from the start of the attribute name when referring to it in JavaScript – you do still need to include it in your HTML though. Notice that if your custom attribute name has a hyphen in it, which ours does, this becomes camel-case when accessed through the dataset (“data-product-category” becomes “productCategory”).
Other Methods and Functions
We have explored getting attributes, but your scripts can also set and remove them. The following code demonstrates setting attributes using the standard JavaScript method and the dataset alternative:
//DOM method theElement.setAttribute('data-product-category', 'sale'); //dataset version theElement.dataset.productCategory = "sale";
To remove an attribute, you can also use either a DOM method or the dataset:
//DOM method theElement.removeAttribute('data-product-category'); //dataset version theElement.dataset.productCategory = null;
Conclusion
Implementing custom attributes in HTML5 is not technically complex in itself, however the real difficulty is in choosing whether it is appropriate to use them in your own projects, and if so how to go about it efficiently. Finally, do remember that it’s still a little early to start using the dataset approach for functions your pages rely on, so be sure to provide an alternative for non-supporting browsers.
Sue Smith works as a Web/ software developer and technical writer based in the UK: see benormal.info for details. Sue has written for various clients including Smashing Magazine and Mobiletuts+. She also does a little Android development and some comedy writing. More articles by Sue Smith
Element: setAttribute() method
Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .
Syntax
Parameters
A string specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document.
A string containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string.
Boolean attributes are considered to be true if they’re present on the element at all. You should set value to the empty string ( «» ) or the attribute’s name, with no leading or trailing whitespace. See the example below for a practical demonstration.
Since the specified value gets converted into a string, specifying null doesn’t necessarily do what you expect. Instead of removing the attribute or setting its value to be null , it instead sets the attribute’s value to the string «null» . If you wish to remove an attribute, call removeAttribute() .
Return value
Exceptions
The specified attribute name contains one or more characters which are not valid in attribute names.
Examples
In the following example, setAttribute() is used to set attributes on a .
HTML
button height: 30px; width: 100px; margin: 1em; >
JavaScript
const button = document.querySelector("button"); button.setAttribute("name", "helloButton"); button.setAttribute("disabled", "");
This demonstrates two things:
- The first call to setAttribute() above shows changing the name attribute’s value to «helloButton». You can see this using your browser’s page inspector (Chrome, Edge, Firefox, Safari).
- To set the value of a Boolean attribute, such as disabled , you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true . The absence of the attribute means its value is false . By setting the value of the disabled attribute to the empty string ( «» ), we are setting disabled to true , which results in the button being disabled.
DOM methods dealing with element’s attributes:
Not namespace-aware, most commonly used methods | Namespace-aware variants (DOM Level 2) | DOM Level 1 methods for dealing with Attr nodes directly (seldom used) | DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used) |
---|---|---|---|
setAttribute (DOM 1) | setAttributeNS | setAttributeNode | setAttributeNodeNS |
getAttribute (DOM 1) | getAttributeNS | getAttributeNode | getAttributeNodeNS |
hasAttribute (DOM 2) | hasAttributeNS | — | — |
removeAttribute (DOM 1) | removeAttributeNS | removeAttributeNode | — |
Specifications
Browser compatibility
BCD tables only load in the browser
Gecko notes
Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use Element.value instead of Element.setAttribute() .
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.