I’m trying to take content from a list (but not including the LI tag wrapped around it) and copy it elsewhere.
I’ve got this fiddle here: http://jsfiddle.net/csaltyj/u5tFb/
I simply cannot figure this out. How do I get this working right?
HTML:
<div id="container">
</div>
<ul>
<li><p>Text 1</p><em>Text 2</em></li>
<li>Gonna copy me too?</li>
<li><h3>We're gonna be in DIVs!</h3></li>
</ul>
<button id="copy">Copy</button>
<button id="clear">Clear DIV</button>
CSS:
#container {
background: #eee;
}
#container .special {
border: 1px solid red;
}
li {
list-style-type: disc;
margin: 1em;
}
jQuery:
$('#copy').click(function() {
$('li').each(function(i) {
$(this).clone().contents().wrap('<div class="special" />').appendTo('#container');
});
});
jQuery:
I believe your problem is that you’re assuming
wrapreturns the wrapper. It’s a perfectly reasonable assumption, but it’s incorrect; it returns the original elements, not the wrapper. So when you append them, it’s as though you hadn’t put them in a wrapper, as the elements are moved out of it and the wrapper is thrown away.I suspect this is more what you’re looking for:
Updated fiddle
Though it would be marginally more efficient to use
$(this).contents().clone()rather than$(this).clone().contents()since you don’t use the cloned wrapperli, just the cloned contents:Updated fiddle
Either way, those put the two elements in your first
liin one wrapperdiv, which I suspect is what you want. Alternately, though, if you really want to wrap each part of what’s in eachliseparately, just move up to the parent element before doing your final append (but that splits out every element in eachliinto its owndiv, which I don’t think is what you want):Updated fiddle