How to move an element into another element?

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

    You can use pure JavaScript, using appendChild() method...

    The appendChild() method appends a node as the last child of a node.

    Tip: If you want to create a new paragraph, with text, remember to create the text as a Text node which you append to the paragraph, then append the paragraph to the document.

    You can also use this method to move an element from one element to another.

    Tip: Use the insertBefore() method to insert a new child node before a specified, existing, child node.

    So you can do that to do the job, this is what I created for you, using appendChild(), run and see how it works for your case:

    function appendIt() {
      var source = document.getElementById("source");
      document.getElementById("destination").appendChild(source);
    }
    #source {
      color: white;
      background: green;
      padding: 4px 8px;
    }
    
    #destination {
      color: white;
      background: red;
      padding: 4px 8px;
    }
    
    button {
      margin-top: 20px;
    }

    Source

    Destination

提交回复
热议问题