Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data attribute on div with js

Tags:

javascript

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!

like image 989
PMaly Avatar asked Feb 13 '13 18:02

PMaly


2 Answers

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')
like image 142
marekful Avatar answered Oct 19 '22 00:10

marekful


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">
like image 34
Harry .Naeem Avatar answered Oct 19 '22 02:10

Harry .Naeem