HTML attributes are used to describe additional qualities or characteristics of the HTML element in question.
The “href” element of the “a” tag, for example, defines the URL of the page to which the link should go.
HTML has a number of attributes that allow you to define various properties for various elements. But what if you wanted to define a property for a non-existent attribute?
Enter HTML data attributes. HTML Data attributes allow you to create your own attributes for storing additional information on standard HTML elements.
Syntax
Defining data attributes for HTML elements is quite simple. You just need to suffix a word to data-* on an HTML element — like data-whatever-you-want, and you’re good to go.
For example, say you have a list of restaurants on a page and for every list item, you want to store its distance from a central location in the HTML, you could do this: <li class=”restaurants” data-distance=”1456789”>Radisson Blue </li>
N.B:
- The data in these data attributes must be of the string type. Data attributes can hold anything that can be string-encoded.
- An HTML element can contain an unlimited amount of data attributes.
- Data attributes cannot have more than one hyphen (-). To separate words, use an underscore.
- data attributes should only be utilized when no other HTML elements or attributes are available. For example, storing an element’s class in a data-class attribute is not suitable.
Use cases of data attributes
Data attributes are usually used by programmers to store information that is constantly changing within an HTML element, so it can be manipulated via JavaScript — like how many times a button has been clicked.
For example, assume we have several like buttons on a page like so: <button class=”like-buttons” data-times_liked=”50”> Like Me</button>
In JavaScript, we can watch out for click events on each button and increment the number of likes. JavaScript provides a dataset property that you can use to read data attributes values off their HTML elements.
const likeButton = document.querySelector(“.like-buttons”);
likeButton.addEventListener(‘click’, () =>
{
likeButton.dataset.times_liked += 1;
})
Blog Credits: Linda Ikechukwu
” Linda Ikechukwu is a Frontend Developer turned Technical Content Consultant. She enjoys strategizing on and creating content that helps tech startups connect with their target audience. “
Comments are closed.