How to move an element into another element?

前端 未结 15 2265
無奈伤痛
無奈伤痛 2020-11-22 03:35

I would like to move one DIV element inside another. For example, I want to move this (including all children):

...
相关标签:
15条回答
  • 2020-11-22 04:34

    What about a JavaScript solution?

    // Declare a fragment:
    var fragment = document.createDocumentFragment();
    
    // Append desired element to the fragment:
    fragment.appendChild(document.getElementById('source'));
    
    // Append fragment to desired element:
    document.getElementById('destination').appendChild(fragment);
    

    Check it out.

    0 讨论(0)
  • 2020-11-22 04:34

    You can use:

    To Insert After,

    jQuery("#source").insertAfter("#destination");
    

    To Insert inside another element,

    jQuery("#source").appendTo("#destination");
    
    0 讨论(0)
  • 2020-11-22 04:35

    You may want to use the appendTo function (which adds to the end of the element):

    $("#source").appendTo("#destination");
    

    Alternatively you could use the prependTo function (which adds to the beginning of the element):

    $("#source").prependTo("#destination");
    

    Example:

    $("#appendTo").click(function() {
      $("#moveMeIntoMain").appendTo($("#main"));
    });
    $("#prependTo").click(function() {
      $("#moveMeIntoMain").prependTo($("#main"));
    });
    #main {
      border: 2px solid blue;
      min-height: 100px;
    }
    
    .moveMeIntoMain {
      border: 1px solid red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="main">main</div>
    <div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>
    
    <button id="appendTo">appendTo main</button>
    <button id="prependTo">prependTo main</button>

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