How to move an element into another element?

前端 未结 15 2266
無奈伤痛
無奈伤痛 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:19

    dirty size improvement of Bekim Bacaj answer

    div { border: 1px solid ; margin: 5px }
    <div id="source" onclick="destination.appendChild(this)">click me</div>
    <div id="destination" >...</div>

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

    You may also try:

    $("#destination").html($("#source"))
    

    But this will completely overwrite anything you have in #destination.

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

    I noticed huge memory leak & performance difference between insertAfter & after or insertBefore & before .. If you have tons of DOM elements, or you need to use after() or before() inside a MouseMove event, the browser memory will probably increase and next operations will run really slow.

    The solution I've just experienced is to use inserBefore instead before() and insertAfter instead after().

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

    my solution:

    MOVE:

    jQuery("#NodesToMove").detach().appendTo('#DestinationContainerNode')
    

    COPY:

    jQuery("#NodesToMove").appendTo('#DestinationContainerNode')
    

    Note the usage of .detach(). When copying, be careful that you are not duplicating IDs.

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

    If the div where you want to put your element has content inside, and you want the element to show after the main content:

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

    If the div where you want to put your element has content inside, and you want to show the element before the main content:

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

    If the div where you want to put your element is empty, or you want to replace it entirely:

    $("#element").html('<div id="source">...</div>');
    

    If you want to duplicate an element before any of the above:

    $("#destination").append($("#source").clone());
    // etc.
    
    0 讨论(0)
  • 2020-11-22 04:33

    Ever tried plain JavaScript... destination.appendChild(source); ?

    onclick = function(){ destination.appendChild(source); }
    div{ margin: .1em; } 
    #destination{ border: solid 1px red; }
    #source {border: solid 1px gray; }
    <!DOCTYPE html>
    <html>
    
     <body>
    
      <div id="destination">
       ###
      </div>
      <div id="source">
       ***
      </div>
    
     </body>
    </html>

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