11

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,753
  • 72
  • 57
  • 129
PMaly
  • 151
  • 1
  • 1
  • 8
  • Try `element.setAttribute('data-stellar-ratio', 'something');` – MCL Feb 13 '13 at 18:09
  • This should help: http://stackoverflow.com/questions/710275/how-to-add-update-an-attribute-to-an-html-element-using-javascript – tymeJV Feb 13 '13 at 18:10
  • 1
    Should probably be `.dataset.stellarRatio = '2';` – Shmiddty Feb 13 '13 at 18:12
  • Isn't it `getElementsByClassName`? – j08691 Feb 13 '13 at 18:13
  • It is a lot easier to manipulate the DOM with the help of jQuery, $(".text").attr('data-stellar-ratio', '2'); But I'm not sure that you want an answer with jQuery in it. – QuentinUK Feb 13 '13 at 18:15
  • `document.getElementsByClassName('text').dataset.stellarRatio = "2";` did not work. Though it worked with `getElementById` . – PMaly Feb 13 '13 at 18:23

4 Answers4

15

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,986
  • 6
  • 37
  • 59
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";
}
marteljn
  • 6,446
  • 3
  • 30
  • 43
2

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,528
  • 2
  • 25
  • 26
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,245
  • 3
  • 20
  • 33