'Move button when clicked

How do I move the button from the div with id of two to the div with id of one when I click the button?

<div id="one">

</div>

<div id="two">
  <button onclick="moveMe"></button>
</div>
function moveMe() {
 // ??
}


Solution 1:[1]

function moveMe() {
  const divTwo = document.getElementById("two")
  const divOne = document.getElementById("one")
  
  const newButton = document.createElement("button")
  newButton.innerText = "Click me"
  
  divOne.appendChild(newButton)
  divTwo.children[1].remove()
}
<div id="one">
<p>
div one
</p>
</div>

<div id="two">
<p>
div two
</p>
  <button onclick="moveMe()">Click me</button>
</div>

Solution 2:[2]

You can try this:

// select the elements
const button = document.querySelector('button');
const firstDiv = document.getElementById('one');

// add eventListener
button.addEventListener('click', moveButton);

// move the button
function moveButton() {
  firstDiv.append(button);
}

Solution 3:[3]

<div id="one">

</div>

<div id="two">
  <button id="btn" onclick="moveMe">MoveMe</button>
</div>

 function moveMe() {
        var divOne = document.querySelector("#one");
        var btn = document.querySelector("#btn");
        divOne.appendChild(btn);
 }

Solution 4:[4]

You can use code below to move the element.

There's some changes that I made on your code,

you can use version 1 or version 2

  • the changes on first version is i add "id" attribute on the element so we don't resort to use the tag only as selector, of course you can also use #two>button to make it more precise
  • the changes on second version is i add a parameter to your function this time it will handle the current element using "this" keyword when calling the function

function moveMe(){
    // one.appendChild(document.querySelector("button"));
    one.appendChild(move);
}

function moveMeV2(element){
    one.appendChild(element);
}
<div id="one">
  <span>one</span>
</div>

<div id="two">
  <span>two</span>
  <button id="move" onclick="moveMe()">Move Me</button>
  <button onclick="moveMeV2(this)">Move Me V2</button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marian150
Solution 2 VoetsT
Solution 3 Haim Abeles
Solution 4 Williams Gunawan