What are data- attributes good for?

Asked by: alf93
Date:
Viewed: 293
Answers: 1
  • 0

Hi,

I’d like to know What are data- attributes good for? And how they are used?

Answers

Answer by: jenniryan

Answered on: 20 Jul 2023

  • 0

In HTML, data attributes are used to store custom data private to the page or application. They are defined by the data-* attribute, where * represents a placeholder for the name of the data attribute. The values of data attributes are strings, and are typically used to store data that is not meant to be displayed to the user or interpreted as part of the content of the page, but rather is meant to be used in the background by scripts.

In JavaScript, you can access the values of data attributes using the getAttribute method. For example, given the following element:

<div id="myElement" data-id="123" data-position="first" data-category="fruits">Apple</div>

You can access the values of the data attributes like this:

const element = document.getElementById('myElement');
const id = element.getAttribute('data-id');
const position = element.getAttribute('data-position');
const category = element.getAttribute('data-category');

You can also use the dataset property of an element to access the values of data attributes. The dataset property is an object that contains a property for each data attribute of the element. The names of the properties are the names of the data attributes, with the data- prefix removed.

For example, you can access the values of the data attributes in the previous example like this:

const element = document.getElementById('myElement');
const id = element.dataset.id;
const position = element.dataset.position;
const category = element.dataset.category;

Note that the dataset property is only supported in modern browsers, so if you need to support older browsers, you should use the getAttribute method instead.

 

Please log in to post an answer!