Move element from one div to another without changing the state

Asked

Viewed 295 times

1

How to move the contents of a div to another div and maintain the status of the elements?

Example: move a input of a div to another, without creating a new input and delete the old one, as in the code below, thus keeping the value typed in the input `.

This code is just a basic example of what I’m trying to do, there’s nothing "fancy".

I could take the value of input old and put it in the new input, but I’m using the input as an example could be any other element.

window.onload = function(){document.getElementsByTagName("input")[0].value="Valor do input";};
function mover(){
  origem = document.getElementById("origem");
  destino = document.getElementById("destino");
  
  destino.innerHTML = origem.innerHTML;
  origem.innerHTML="";
}
<div style="background:green" id="origem"><input id="input"></div>
<div style="background:red" id="destino"></div>
<button onclick="mover()">MOVER</button>

1 answer

2


You can use the method children to obtain all child elements of the parent element and the appendChild to add the elements to the new parent element.

function mover() {
    origem = document.getElementById("origem");
    destino = document.getElementById("destino");

    filhos = Array.prototype.slice.call(origem.children); //Convertendo HTMLCollection para Array
    filhos.forEach(function(element, index) {
        destino.appendChild(element);
    });
}

The method appendchild remove the current parent element node before adding it to the new parent element.

  • Like I said in the question Como mover o conteúdo de uma div, there may be more than one element, the way you presented I would have to select each element individually, it would not be feasible. So I used innerHTML to take everything inside the div

  • @Markvaaz, I updated the response.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.