If the browser does not support .dataset
then you can use .setAttribute
to change the value and .getAttribute
to get it, like this:
var teste = document.getElementById('teste');
teste.setAttribute("data-delay-duration", "100");
console.log("data-delay-duration:", teste.getAttribute("data-delay-duration"));
console.log("source:", document.body.innerHTML);
<span id="teste" data-delay-duration="800"></span>
Just to be aware, although I can say that IE8, 9 and 10 have partial support for dataset
and data-
on link , in fact they refer to the use of getAttribute
itself, ie .dataset
is not available, according to their message:
Partial support refers to being able to use data- * attributes and access them using getAttribute.
So if you need one of these browsers you will have to use .setAttribute
.
If it is to apply to multiple elements, such as NodeList
, you can use any method for this (depending on the elements), as some examples:
-
document.getElementsByTagName
-
document.getElementsByName
-
document.querySelectorAll
I think querySelectorAll
is the simplest to use, like this:
var els = document.querySelectorAll('.foo, .baz');
for (var i = 0, j = els.length; i < j; ++i) {
els[i].setAttribute("data-delay-duration", "100");
}
console.log("source:", document.body.innerHTML);
<span class="foo" data-delay-duration="800"></span>
<span class="bar" data-delay-duration="800"></span>
<span class="baz" data-delay-duration="800"></span>
<span class="foo" data-delay-duration="800"></span>
<span class="foo" data-delay-duration="800"></span>
<span class="foo" data-delay-duration="800"></span>
Note that in this example only elements with class=foo
and class=baz
have the value changed
Note: To check if the DOM already loaded you can run the script like this:
(function () { //Isola o escopo para evitar conflito com outras funções e vars
function trigger() {
var els = document.querySelectorAll('.foo, .baz');
for (var i = 0, j = els.length; i < j; ++i) {
els[i].setAttribute("data-delay-duration", "100");
}
}
if (document.readyState !== "loading") {
trigger();
} else {
document.addEventListener("DOMContentLoaded", trigger);
}
})();