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 havedata-single="true"
in its markup.
Example:
HTML
<div class="ele">Hi</div>
Javascript
let ele = document.querySelector(".ele");
ele.dataset.single = "true";
The HTML element will now look like:
<div class="ele" data-single="true">Hi</div>
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 havedata-single="true"
in it's markup.
Example
HTML
<div class="ele">Hi</div>
Javascript
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"
Example
HTML
<div class="ele">Hi</div>
Javascript
let ele = document.querySelector(".ele");
ele.dataset.gumroadSingleProduct = "true";
The HTML element will now look like:
<div class="ele" data-gumroad-single-product="true">Hi</div>
The camelCase will be converted to the dashes as explained in these MDN docs.