Joanna Joanna - 1 month ago 7
Javascript Question

Moving items between two lists in JavaScript

I want to move items between two lists. All list items have buttons within them, once this button is clicked, item should be moved to the other list. I have created JavaScript event but it works only one way - so the item can be moved once e.g. from list1 to list2 but when I try to click on the button again, it doesn't work. Can you look at me code and advise how can I assign my event also to newly created items (these that just have been moved)?

document.addEventListener("DOMContentLoaded", function () {

var buttons = document.querySelectorAll(".moveBtn");

var list1 = document.getElementById("list1");

var list2 = document.getElementById("list2");

function moveItem(e) {
var newItem = document.createElement("li");

if (this.parentElement.parentElement.id === "list1") {
list2.appendChild(newItem);


} else {
list1.appendChild(newItem);

}

newItem.innerHTML = this.parentElement.innerHTML;
this.parentElement.parentNode.removeChild(this.parentElement);

}

for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", moveItem);
}

})

Answer

Rather than destroying the old element and creating a new one, just move the element:

function moveItem(e) {
    var moveTo = this.parentElement.parentElement.id == "list1" ? list2 : list1;
    moveTo.appendChild(this.parentElement);
}

Note also that there's no need to match on id; you can match on the actual element:

function moveItem(e) {
    var moveTo = this.parentElement.parentElement == list1 ? list2 : list1;
    moveTo.appendChild(this.parentElement);
}

Live Example:

document.addEventListener("DOMContentLoaded", function() {
    var buttons = document.querySelectorAll(".moveBtn");
    var list1 = document.getElementById("list1");
    var list2 = document.getElementById("list2");

    function moveItem(e) {
        var moveTo = this.parentElement.parentElement == list1 ? list2 : list1;
        moveTo.appendChild(this.parentElement);
    }

    for (var i = 0; i < buttons.length; i++) {
        buttons[i].addEventListener("click", moveItem);
    }
});
#list1 {
  border: 1px solid green;
}
#list2 {
  border: 1px solid blue;
}
<div id="list1">
  <div>
    Item 1
    <button class="moveBtn">Move</button>
  </div>
  <div>
    Item 2
    <button class="moveBtn">Move</button>
  </div>
  <div>
    Item 3
    <button class="moveBtn">Move</button>
  </div>
</div>
<div id="list2">
  <div>
    Item 4
    <button class="moveBtn">Move</button>
  </div>
  <div>
    Item 5
    <button class="moveBtn">Move</button>
  </div>
  <div>
    Item 6
    <button class="moveBtn">Move</button>
  </div>
</div>