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");
2
  • 1
    working.. jsfiddle.net/76MDE/4 Commented Jul 23, 2014 at 10:59
  • 1
    It's working exactly as expected, jQuery's data() stores data in an internal object, it does not set attributes, that would be attr() Commented Jul 23, 2014 at 11:00

4 Answers 4

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

Comments

1

Use this :

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

Demo

Comments

0

Fiddle

USE THIS

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

2 Comments

Actually it has to be $('.name').attr("data-element", "name");
Question asked is to "add a data attribute with a value to a li".. Wat else i can add in this...
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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.