Muhammet
Muhammet

Reputation: 3308

Why jQuery data won't work with append?

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

Upvotes: 0

Views: 208

Answers (1)

sahbeewah
sahbeewah

Reputation: 2690

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.

Upvotes: 5

Related Questions