- How to set the data attribute of an element with Javascript?
- dataset Property
- setAttribute() method
- How to set a data attribute with Javascript if the attribute has dashes or hyphens?
- HTMLElement: dataset property
- Name conversion
- Accessing values
- Setting values
- Value
- Examples
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Data Attributes In JavaScript
- Data Attribute Introduction
- Reading Data Attributes
- Writing Data Attributes
- Updating Data Attributes
- Delete Data Attributes
- Real World Example
- Conclusion
How to set the data attribute of an element with Javascript?
There are 2 ways to set the data attribute of an element using Javascript. The way I typically set the data attribute is with the dataset property, and the other way is using the setAttribute() method.
dataset Property
To set the data attribute with the dataset property do the following:
- Grab the element (i.e let ele = document.querySelector(«.ele») )
- Using the dataset property of that element, set the data attribute. For example, if you want to add a «data-single» attribute then do ele.dataset.single = «true» . The element will now have data-single=»true» in its markup.
let ele = document.querySelector(".ele"); ele.dataset.single = "true";
The HTML element will now look like:
class="ele" data-single="true">Hi
setAttribute() method
This is another way to achieve the same thing of adding the data attribute using Javascript.
- Grab the element (i.e let ele = document.querySelector(«.ele») )
- Using the setAttribue() method, set the data attribute. For example, if you want to add a «data-single» attribute then do ele.setAttribute(«data-single», «true»);» . The element will now have data-single=»true» in it’s markup.
let ele = document.querySelector(".ele"); ele.setAttribute("data-single", "true");
How to set a data attribute with Javascript if the attribute has dashes or hyphens?
If the data attribute you are trying to set contains dashes/hyphens then use camelCase convention in the JS.
For example, if you want to set the data attribute of «data-gumroad-single-product» to true, you need to do dataset.gumroadSingleProduct = «true»; , this would set the data attribute in the HTML to look like data-gumroad-single-product=»true»
let ele = document.querySelector(".ele"); ele.dataset.gumroadSingleProduct = "true";
The HTML element will now look like:
class="ele" data-gumroad-single-product="true">Hi
The camelCase will be converted to the dashes as explained in these MDN docs.
Want to learn how to code and make money online? Check out CodingPhase (referral link)
HTMLElement: dataset property
The dataset read-only property of the HTMLElement interface provides read/write access to custom data attributes ( data-* ) on elements. It exposes a map of strings ( DOMStringMap ) with an entry for each data-* attribute.
Note: The dataset property itself can be read, but not directly written. Instead, all writes must be to the individual properties within the dataset , which in turn represent the data attributes.
An HTML data-* attribute and its corresponding DOM dataset.property modify their shared name according to where they are read or written:
The attribute name begins with data- . It can contain only letters, numbers, dashes ( — ), periods ( . ), colons ( : ), and underscores ( _ ). Any ASCII capital letters ( A to Z ) are converted to lowercase.
The property name of a custom data attribute is the same as the HTML attribute without the data- prefix, and removes single dashes ( — ) for when to capitalize the property’s «camelCased» name.
In addition to the information below, you’ll find a how-to guide for using HTML data attributes in our article Using data attributes.
Name conversion
A custom data attribute name is transformed to a key for the DOMStringMap entry by the following:
- Lowercase all ASCII capital letters ( A to Z );
- Remove the prefix data- (including the dash);
- For any dash ( U+002D ) followed by an ASCII lowercase letter a to z , remove the dash and uppercase the letter;
- Other characters (including other dashes) are left unchanged.
The opposite transformation, which maps a key to an attribute name, uses the following:
- Restriction: Before transformation, a dash must not be immediately followed by an ASCII lowercase letter a to z ;
- Add the data- prefix;
- Add a dash before any ASCII uppercase letter A to Z , then lowercase the letter;
- Other characters are left unchanged.
For example, a data-abc-def attribute corresponds to dataset.abcDef .
Accessing values
- Attributes can be set and read by the camelCase name/key as an object property of the dataset: element.dataset.keyname .
- Attributes can also be set and read using bracket syntax: element.dataset[‘keyname’] .
- The in operator can check if a given attribute exists: ‘keyname’ in element.dataset .
Setting values
- When the attribute is set, its value is always converted to a string. For example: element.dataset.example = null is converted into data-example=»null» .
- To remove an attribute, you can use the delete operator: delete element.dataset.keyname .
Value
Examples
div id="user" data-id="1234567890" data-user="carinaanand" data-date-of-birth> Carina Anand div>
const el = document.querySelector("#user"); // el.id === 'user' // el.dataset.id === '1234567890' // el.dataset.user === 'carinaanand' // el.dataset.dateOfBirth === '' // set a data attribute el.dataset.dateOfBirth = "1960-10-03"; // Result on JS: el.dataset.dateOfBirth === '1960-10-03' // Result on HTML:Carina Ananddelete el.dataset.dateOfBirth; // Result on JS: el.dataset.dateOfBirth === undefined // Result on HTML:Carina Anandif (!("someDataAttr" in el.dataset)) el.dataset.someDataAttr = "mydata"; // Result on JS: 'someDataAttr' in el.dataset === true // Result on HTML:Carina Anand>
Specifications
Browser compatibility
BCD tables only load in the browser
See also
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.
Data Attributes In JavaScript
One of the best ways to store data in HTML is with data attributes. These data attributes can be used to do some pretty cool things in CSS without the need for JavaScript, as seen in this article, but data attributes are most useful when combined with JavaScript. In this article I will teach you exactly how to use data attributes in JavaScript and what makes them so powerful.
Data Attribute Introduction
To get started talking about data attributes we need to first have some HTML with data attributes. To create a data attribute in HTML we just need to add a custom attribute to our HTML element that starts with data- .
div id="test-div" data-first-name="Kyle" data-last-name="Cook" data-active >div>
Reading Data Attributes
We now have a div with three custom data attributes. Now let’s move over to JavaScript to see how we would access these data attributes.
const div = document.getElementById("test-div") console.log(div.dataset)
The dataset property on an element will return a DOMStringMap which is essentially just an object that contains all the custom data attributes of an element. Our dataset looks like this.
active: "" firstName: "Kyle" lastName: "Cook" >
You will notice two interesting things about this.
First, all of our properties are converted from snake case, first-name , to camel case, firstName . This is because in JavaScript object properties are primarily written as camel case so this just makes working with the JavaScript object much easier.
Second, the active property has a value of «» . This is because any data attribute without a value is assumed to have an empty string as its value.
Now in order to access an individual data attribute we just access it like a property on an object since dataset is just an object.
const div = document.getElementById("test-div") console.log(div.dataset.firstName) // Kyle console.log(div.dataset.lastName) // Cook
Writing Data Attributes
In order to create a new data attribute in JavaScript we just need to add a new property to the dataset object with a value.
const div = document.getElementById("test-div") div.dataset.test = "Hi" console.log(div.dataset.test) // Hi
This will update the dataset object and our HTML which means our HTML will look like this.
div id="test-div" data-test="Hi" data-first-name="Kyle" data-last-name="Cook" data-active >div>
Updating Data Attributes
Let’s say that we now want to update the value of a data attribute. This is incredibly easy since it works just like a normal object. We just need to set the value of our dataset property to the new value and it will update the HTML for us.
const div = document.getElementById("test-div") div.dataset.firstName = "Sally" console.log(div.dataset.firstName) // Sally
This will update the dataset object and our HTML which means our HTML will look like this.
div id="test-div" data-first-name="Sally" data-last-name="Cook" data-active >div>
Delete Data Attributes
Deleting data attributes is a bit different since we need to actually remove the property from our object. This is because if we try setting the value to undefined or null the dataset object will still have a reference to that property with that value of undefined or null and will set the value of our HTML data attribute to the string null or undefined .
To delete an element we need to use the delete keyword to remove it completely from the object.
const div = document.getElementById("test-div") delete div.dataset.active console.log(div.dataset.active) // undefined
This will update the dataset object and our HTML which means our HTML will look like this.
div id="test-div" data-first-name="Sally" data-last-name="Cook">div>
Real World Example
Now let’s combine all this into a real world example. Let’s say you have the following HTML.
button>Open Modal 1button> button>Open Modal 2button> div id="modal-1">Modal 1div> div id="modal-2">Modal 2div>
You want to write JavaScript so that the first button opens modal 1 and the second button opens modal 2, but we want to do this in a way that is reusable so if we add a third button that opens a new modal we don’t need to write any new JavaScript code.
This may sound really difficult at first, but essentially all we need is some way to link each button to their respective modal in the HTML. This is where data attributes come in.
We can set a custom data attribute on each button that references the modal they are linked to. In our case we can use the id of each modal as our reference.
button data-modal-id="modal-1">Open Modal 1button> button data-modal-id="modal-2">Open Modal 2button> div id="modal-1">Modal 1div> div id="modal-2">Modal 2div>
So now we have a way to access the id of the modal linked to each button inside JavaScript.
const buttons = document.querySelectorAll("[data-modal-id]") buttons.forEach(button => button.addEventListener("click", () => const modalId = button.dataset.modalId const modal = document.getElementById(modalId) modal.classList.add("show") >) >)
In the above code we are selecting all elements that contain our custom data-modal-id attribute. We are then looping through them and adding a click event listener to each one. Inside this event listener we are using the modal id to get the modal link to that button and adding the show class so it is now visible.
This code is also flexible since it will get any element with the custom data-modal-id attribute. This means that if we add a new button that references a new modal we won’t need to write any additional JavaScript.
Conclusion
Data attributes in JavaScript are incredibly useful. They allow you to write extremely flexible code which means you can spend more time writing the HTML for your project and less time worrying about writing a custom event listener for each new element you add.