Question

In order to do some DOM manipulation efficiently I am detaching an element. In the process, I came across this interesting situation:

var $holder = $("#d");
var $wrapper = $("<div>").css("border","1px solid red");
$holder.wrap($wrapper);
$holder.detach();
$wrapper.append($holder);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="d">a</div>

Whereby a div with the letter "a" in it is wrapped by a div with a red border. Then the div with the letter "a" is detached. Then the wrapping div is appending the detached "a". However, the letter "a" never re-appears.

What did I miss? What did I do wrong? How can I get the "a" back?

Was it helpful?

Solution

wrap() creates a HTML structure on the fly and inserts it into the DOM, that's why something like :

$(element).wrap('<div><span></span></div>')

works, so the variable $wrapper is not the same as the element that was actually created and inserted by wrap(), so you have get the element from the DOM again :

var $holder = $("#d");
var $wrapper = $('<div />', {style:'border:1px solid red;', id:'wrapper'});
$holder.wrap($wrapper);
$holder.detach();
$('#wrapper').append($holder);

FIDDLE

from the documentation:

The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.

OTHER TIPS

Just do $holder.detach($wrapper);

edit: here's the working Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top