javascript - Why jQuery data won't work with append? -


i appending data server unordered list, setting data-id attribute data() doesn't work, 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 append so, prefer first option.

$('#menu').append('<li data-id="5">home</li>'); 

the .data() method read data-* attribute secondary function. first tries read data jquery's internal cache key-value pair (attached element).

the main takeaway is, doesn't work other way around. i.e. .data() not put attributes on element. store data in jquery's internal cache associated element.


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -