In jQuery's docs for wrap()
is the following:
A copy of this structure will be wrapped around each of the elements in the set of matched elements.
This means that when I save the element that I want to wrap around another element into a variable, after wrapping, the variable doesn't point to the wrapping element anymore. So e.g. adding another CSS class to it after wrapping doesn't happen to the wrapping element (which is a copy) but only to the original one.
In contrast to this, append()
doesn't copy the element.
$(document).ready ->
$appendEl = $("<span href='#'>appended</span>")
$('#append').append($appendEl) # Append
$appendEl.addClass 'new-class' # Works
$wrapEl = $("<span href='#'>wrapped</span>")
$('#wrap').wrap($wrapEl) # Wrapp
$wrapEl.addClass 'new-class' # Doesn't work
I have created a CodePen to demonstrate this: http://codepen.io/jmuheim/pen/QNQZKw
So why does wrap()
copy the element, and how can I make the code above work for wrap()
?
And why does jQuery copy the element when doing wrap()
? Doesn't this make much overhead and "pollute" things?