Ticket #4346 (closed bug: worksforme)
Data missing after adding to two elements.
| Reported by: | kondziu | Owned by: | |
|---|---|---|---|
| Priority: | major | Milestone: | 1.4 |
| Component: | data | Version: | 1.4a1 |
| Keywords: | data, missing, multi element add | Cc: | |
| Blocking: | Blocked by: |
Description
jQ 1.2.6 and 1.3.2
jQuery('body').append(jQuery('<ul id="list1">')); jQuery('body').append(jQuery('<ul id="list2">'));
creating element with data var li = jQuery('<li>').text('x').data('foo', 'bar');
console.info(jQuery.data(li[0])); -> 2 console.info(jQuery.data(li[0], 'foo')); -> bar
after adding to two elements ... jQuery('#list1, #list2').prepend(li);
console.info(jQuery.data(jQuery('#list1 li')[0])); -> 7 (OK) console.info(jQuery.data(, 'foo')); -> undefined
console.info(jQuery.data(jQuery('#list2 li')[0])); -> 8 (OK) console.info(jQuery.data(jQuery('#list2 li')[0], 'foo')); -> undefined
data is missing
Change History
comment:2 Changed 4 years ago by dmethvin
jQuery('#list1, #list2').prepend(li);
Since there are two elements in the jQuery object, the prepend is cloning the original li and appending the clone to the second element. The clone does not have the data.
I think the logic behind this is that copying all the .data to all elements would be expensive (and remember that .data includes all events as well). You still have the option to explicitly copy the data, or better still attach events and data after the implicit cloning occurs.
The docs aren't clear on this, so I'd suggest clearly documenting the behavior to resolve the ticket.
comment:4 Changed 4 years ago by dmethvin
- Component changed from unfilled to data
- Milestone changed from 1.3.2 to 1.3.3
comment:5 Changed 3 years ago by john
- Status changed from new to closed
- Version changed from 1.2.6 to 1.4a1
- Resolution set to worksforme
In this case you should clone the elements so that you explicitly carry over the data from the old ones (considering that what you describe doesn't carry over events either, this seems like a fair request).
Since #4191 is already fixed this should be as simple as doing .clone(true).
Please follow the bug reporting guidlines and use jsFiddle when providing test cases and demonstrations instead of pasting the code in the ticket.

//jQ 1.2.6 amd 1.3.2 jQuery('body').append(jQuery('<ul id="list1">')); jQuery('body').append(jQuery('<ul id="list2">')); //creating element with data var li = jQuery('<li>').text('x').data('foo', 'bar'); console.info(jQuery.data(li[0])); //-> 2 console.info(jQuery.data(li[0], 'foo')); //-> bar //after adding to two elements jQuery('#list1, #list2').prepend(li); console.info(jQuery.data(jQuery('#list1 li')[0])); //-> 7 (OK) console.info(jQuery.data(jQuery('#list1 li')[0], 'foo')); // -> undefined console.info(jQuery.data(jQuery('#list2 li')[0])); //-> 8 (OK) console.info(jQuery.data(jQuery('#list2 li')[0], 'foo')); // -> undefined //data is missing