0

I am appending data from server to an unordered list, however setting data-id attribute with data() doesn't work, but attr() does.


When using data():

Appends <li>Home</li>

$('#menu').append($('<li>').text("Home").data('id', 5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
</ul>

When using attr():

Appends <li data-id="5">Home</li>

$('#menu').append($('<li>').text("Home").attr('data-id', 5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
</ul>

I know I could append it like so, but prefer the first option.

$('#menu').append('<li data-id="5">Home</li>');
Muhammet
  • 3,288
  • 13
  • 23

1 Answers1

5

The .data() method will read the data-* attribute as a secondary function. But what it first tries to do is read the data from jQuery's internal cache as a key-value pair (attached to the element).

The main takeaway is, it doesn't work the other way around. I.e. .data() will not put attributes on an element. It will just store data in jQuery's internal cache to be associated with that element.

sahbeewah
  • 2,690
  • 1
  • 12
  • 18
  • Yes that's correct. It will first check if data has been set before, and if it has it will read it, irrespective of the html element's attributes. If it so happens that data was never called, it will try to read the associated data-* attribute. – sahbeewah Feb 23 '16 at 13:19
  • Accidentally deleted the first comment, thanks for the explanation, makes total sense now. – Muhammet Feb 27 '16 at 14:37