Set data attribute for div using js

I have a bunch of div.textBox that I want to apply a data attribute to it.

Here I want to finish:

<div class="text" data-stellar-ratio="2"> 

I tried:

 document.getElementByClassName('text').dataset.stellar.ratio = "2"; 

But it does not work ...

Help!

+4
source share
3 answers
 document.getElementsByClassName('text')[0].setAttribute('dataset-stellar-ratio', '2') 
+2
source

setAttribute does not quite work in all browsers. http://www.w3schools.com/jsref/met_document_createattribute.asp has an example that will certainly work well.

 var att=document.createAttribute("whatever"); att.value="someting"; document.getElementById('mydivid').setAttributeNode(att); 
+1
source

You got getElementsByClassName wrong, and you need to iterate over the set of elements and change stellar.ration to stellarRatio .

 var eles = document.getElementsByClassName('text'); for (var x = 0; x < eles.length; x++){ eles[x].dataset.stellarRatio = "2"; } 
0
source

All Articles