user3613245
user3613245

Reputation: 79

Adding data attribute value not working

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

Upvotes: 1

Views: 964

Answers (4)

brainbowler
brainbowler

Reputation: 675

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

Upvotes: 0

Spokey
Spokey

Reputation: 10994

.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");

Upvotes: 4

PraJen
PraJen

Reputation: 606

Fiddle

USE THIS

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

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Use this :

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

Demo

Upvotes: 1

Related Questions