Set data attribute on div with js

setAttribute doesn't 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);

As documented

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

More precisely, a NodeList is returned and can be accessed as an array. The first element the selector finds is accessed via index 0.

document.getElementsByClassName('text')[0].setAttribute('data-stellar-ratio', '2')

You spelled getElementsByClassName wrong and you need to iterate over the collection 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";
}

Tags:

Javascript