jQuery .wrap() not wrapping around a cloned element

前端 未结 2 1049
说谎
说谎 2021-02-08 01:37



        
相关标签:
2条回答
  • 2021-02-08 02:18

    The confusing part is 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 them already having been inserted into the DOM.

    0 讨论(0)
  • 2021-02-08 02:26

    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.

    0 讨论(0)
提交回复
热议问题