简体   繁体   中英

How can I make a task in my Javascript to-do list appear on a new list item?

I am trying to make a to-do list in JavaScript (and HTML/CSS) and I managed to make the add button work with the following code:

function addTask() {
  let task = document.querySelector("li");
  let inputVal = document.getElementById("task").value;
  task.innerHTML = inputVal;
}

However, whenever I write something in the input and press my add button, the same list element changes instead of appearing on a new list element. Does anyone know how to change it or add code so that a new task appears on a new list element? My HTML code is as follows:

<h1>To-Do List</h1>
    <h2>Today</h2>
    <ul>
        <li id="list"></li>
        <li id="list"></li>
        <li id="list"></li>
        <li id="list"></li>
        <li id="list"></li>
     </ul>
    <input type="text" id="task" value=""> <br>
    <button onclick="addTask()" type="button" id="add">Add task</button>

i think you need to modify like this:

function addTask() {
  let task = document.createElement("li");
  let inputVal = document.getElementById("task").value;
  let todo = document.getElementById("todo");
  task.innerHTML = inputVal;
  todo.appendChild(task);
}

and your html code

<h1>To-Do List</h1>
<h2>Today</h2>
<ul id="todo"></ul>
<input type="text" id="task" value=""> <br>
<button onclick="addTask()" type="button" id="add">Add task</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM