13

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!

6
  • Try element.setAttribute('data-stellar-ratio', 'something'); Commented Feb 13, 2013 at 18:09
  • This should help: stackoverflow.com/questions/710275/… Commented Feb 13, 2013 at 18:10
  • 1
    Should probably be .dataset.stellarRatio = '2'; Commented Feb 13, 2013 at 18:12
  • Isn't it getElementsByClassName? Commented Feb 13, 2013 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. Commented Feb 13, 2013 at 18:15

4 Answers 4

16

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')
Sign up to request clarification or add additional context in comments.

Comments

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";
}

Comments

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);
<div id="mydivid">Javascript is going to set data-attribute for this DIV</div>

Comments

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">

1 Comment

it will not work with pure Javascript. It requires jQuery

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.