I'm using jQuery, I have a simple list
<ul id="list">
<li data-kind="foo">Foo1</li>
<li data-kind="foo">Foo2</li>
<li data-kind="foo">Foo3</li>
</ul>
in which I want to add this new element
<li data-kind="foo">Foo4</li>
I think this code should do the job
new_foo = jQuery('<li/>').data('kind', 'foo').text('Foo4');
new_foo.appendTo(jQuery('#list'));
but it works only half, it correctly adds the new <li> with 'Foo4' inside but it doesn't add the data-kind to the <li>
Checking in Chrome console I see that new_foo HAS data-kind="foo" but actually I can't see it in Chrome inspector and if I try in console to do
$('#list').find('li')
I see all items with data-kind EXCEPT the freshly added one.
Any idea why appendTo seems to ignore data fields?
Thank you!
EDIT1 Thanks to Gautam3164's suggestion I saw that using append() instead appendTo() it works. It seems that appendTo() doesn't preserve data attributes while append() does
EDIT2 Fixed error in my code example, there was a 'message' variable but it was 'new_foo' one
EDIT3 I need the presence of data-kind="foo" because I have a checkbox (with 'filter_switch' class) to show/hide items having data-kind="foo". When I was using .data() it didn't work with freshly created items, while using .attr() it works as expected.
Code is something like:
jQuery('.filter_switch').click(function(){
elem = jQuery(this);
if (elem.prop('checked')) {
jQuery('li[data-kind="' + elem.data('kind') + '"]:hidden').show();
} else {
jQuery('li[data-kind="' + elem.data('kind') + '"]:visible').hide();
}
Thank you very much to everybody, this was my first question on stackoverflow and you were all amazing and very helpful! :)