1

I am trying to add a data attribute with a value to a li, but for some reason its not working. Iv done this before on divs but for some reason its not working correctly now.

Here is my jsfiddle http://jsfiddle.net/76MDE/1/

Here is my code.

<ul class="title-area">
    <li class="name">
        <h1><a href="#">cool</a></h1>
    </li>
</ul>

$('.name').data("element", "name");
TylerH
  • 20,799
  • 66
  • 75
  • 101
user3613245
  • 79
  • 2
  • 11

4 Answers4

4

.data() does not add the data-* attribute. It creates a jQuery object and it will be stored internally in a jQuery cache variable.

If you want to set the attribute you must use .attr()

$('.name').attr("data-element", "name");
Spokey
  • 10,974
  • 2
  • 28
  • 44
1

Use this :

$('.name').attr("data-element", "name");

Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

Fiddle

USE THIS

$('.name').attr("data", "element");
PraJen
  • 606
  • 3
  • 11
0

It IS working, as you can verify by putting a:

alert($('.name').data("element"));

It's only that the HTML is not modified.

If you want to see it in the HTML, too, use the following:

$('.name').attr("data-element", "name");
brainbowler
  • 667
  • 5
  • 17