문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

Just do $holder.detach($wrapper);

edit: here's the working Fiddle

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top