Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move LI to from one UL to another in vanilla JavaScript?

Tags:

javascript

I'm trying to make a very simple "to-do" list application. But I'm having trouble moving my list items from the "To-do" list, to the "Done" list.

Any help would be very appreciated.

This is my code so far.

HTML

<html>
<head>
    <script src="js/main.js"></script>
    <link rel="stylesheet" href="css/css.css">
    <title>Inlämingsuppgift</title>
</head>
<body>
    
    <input type="text" id="input" placeholder="Add a to-do"></input> <button onclick="addToDo()">Add</button>
    <h1>To do</h1>
    <ul id="list1">
    </ul>
    <h1>Done</h1>
    <ul id="list2">
    </ul>
</body>

JS

function addToDo() {
    var input = document.getElementById("input").value + " ";
    var list = document.getElementById("list1");
    var li = document.createElement("li");
    li.className = "selected";
    var doneButton = document.createElement("button");
    doneButton.innerHTML = "Done";
    doneButton.onclick = moveToDo;
    doneButton.className = "move";
    li.appendChild(document.createTextNode(input));
    li.appendChild(doneButton);
    list.appendChild(li);
}

function moveToDo() {
    document.querySelector('.move').click(function() {
        document.querySelector('#list2').insertAdjacentHTML("beforeend",'<li>', document.querySelector('#list1 .selected').text(), '</li>');
        document.querySelector('#list1 .selected').remove();
    });
}
like image 503
Emil Avara Avatar asked Nov 22 '25 22:11

Emil Avara


1 Answers

No need to create and delete, appending an existing element will move it:

function moveItem() {
  const
    origin = document.getElementById('origin'),
    target = document.getElementById('target'),
    el = origin.firstElementChild;
  if (el)
    target.append(el);
}
<div id="container">
  <input type="button" onclick="javascript:moveItem()" value="move 1 li from origin to target" /><br>
  <span>Origin</span>
  <ul id="origin">
    <li>Origin entry 1</li>
    <li>Origin entry 2</li>
    <li>Origin entry 3</li>
  </ul>
  <br>
  <span>Target</span>
  <ul id="target">
  </ul>
</div>
like image 52
netizen Avatar answered Nov 25 '25 12:11

netizen