jQuery .wrap() not wrapping around a cloned element

£可爱£侵袭症+ 提交于 2019-12-03 06:38:29

The key is this line in the .wrap() documentation:

This method returns the original set of elements for chaining purposes.

.wrap() only operates on an element already in the DOM. So, you will need to insert it, then wrap it.

The confusing part might have been to You that .wrap() returns the inner element, not the parent element.

So you have to use the parent object of the wrapped one as follows:

var $divA= $("<div/>").addClass('classA'),
    $divB= $("<div/>").addClass('classB');

console.log( $divA.wrap($divB).parent() );

($divA.parent() is equal to $divB after the wrapping)

So the key part is that $divA.wrap($divB) returns $divA, NOT $divB

see the reference:

This method returns the original set of elements for chaining purposes.

Please note: The elements DON'T have to be in the DOM, jQuery can operate on them without already having been inserted into the DOM.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!