javascriptjquerycustom-data-attributejquery-data

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

Solution

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