10

I've got a bunch of div.textBox that I want to apply data attribute to it.

Here's what I want to end up with :

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

I've tried :

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

But it's not working...

Help!

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
PMaly
  • 143
  • 1
  • 1
  • 8

4 Answers4

13

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')
marekful
  • 14,178
  • 5
  • 35
  • 56
1

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";
}
marteljn
  • 6,258
  • 3
  • 29
  • 42
1

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);
TheBrain
  • 5,350
  • 2
  • 23
  • 25
1

You can add data attribute to any element in html using the following statement:

$('#id_of_element').attr('data-id', 'your_value');

It will render as follows for a div:

<div data-id="your_value">
Harry .Naeem
  • 1,135
  • 3
  • 18
  • 31