Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery appendTo with some data = append element without data

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! :)

like image 467
SDp Avatar asked Feb 26 '26 23:02

SDp


1 Answers

The data is there its just not displayed in the markup displayed in the debugging tool. I assume jQuery stores this data as something other than an attribute.

var new_foo = jQuery('<li/>').data('kind', 'foo2').text('Foo4');
new_foo.appendTo($("#list"));

alert($("li:eq(3)").data("kind")); //alerts foo2

Working Example http://jsfiddle.net/JB549/

You will also notice that when you change data on an element the changes are not reflected in the markup.

//Notice that changes are not reflected
$("li:eq(0)").data("kind", "notFoo");
alert($("li:eq(0)").parent().html()); //markup doesn't contain notFoo

I'm just speculating but jQuery is managing this data internally. Which is most likely why you must prefix these attributes with data-. It provides jQuery the hook to grab the attribute and manage it.

Update Example http://jsfiddle.net/JB549/2/

This post provides some further insight.

like image 116
Kevin Bowersox Avatar answered Feb 28 '26 22:02

Kevin Bowersox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!