Cannot join jQuery wrapper

Why can't you add the item that you use to transfer another, see the example below?

var $test = $('.test'), $test1 = $('.test1'), $move = $('.move'), $testWrapper = $('<div class="test-wrapper"></div>'), $test1Wrapper = $('<div class="test1-wrapper"></div>'); $test.wrap($testWrapper); // move item and return to wrapper $move.append($test); $testWrapper.append($test); // this is the line that does not work? console.log($testWrapper); // still seems to be a jquery object? $test1.after($test1Wrapper); // if you place the element after instead of using it to wrap, then it works? $move.append($test1); $test1Wrapper.append($test1); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test">test</div> <div class="test1">test 1</div> <div class="move"></div> 
+5
source share
1 answer

wrap() seems to clone the markup of the provided element to wrap, rather than the actual element itself. You can see it in the developer tools when you use console.log($testWrapper) and hover over this line in the browser console: usually the DOM element should be selected, but it is not. So what the $testWrapper variable refers to after completion is still (jQuery collection) a node that is not bound to the DOM.

 var $test = $('.test'), $test1 = $('.test1'), $move = $('.move'), $testWrapper = $('<div class="test-wrapper"></div>'); $test.wrap($testWrapper); // move item and return to wrapper $move.append($test); console.log($testWrapper); // <= if you hover this element in the browser console, it doesn't highlight the actual DOM element either; that how you can visully detect that it not the same element! $testWrapper = $('.test-wrapper'); // select the actual DOM element that has been created for wrapping $testWrapper.append($test); // now it will work! 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test">test</div> <div class="move"></div> 
+3
source

Source: https://habr.com/ru/post/1272997/


All Articles