I currently have this code in JavaScript
function addTask() {
// Declaring Variables
var item = document.getElementById("text_field").value;
var text = document.createTextNode(item);
var list_element = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
list_element.appendChild(checkbox);
list_element.appendChild(text);
document.getElementById("todo-list").appendChild(list_element);
}
This works fine to create a list, but the list items are added at the bottom of the html list. How do I add the new user input to the top of the html list?
I think you can place them in an array then reverse them. this will be an example below
function addTask() {
// Declaring Variables
var item = document.getElementById("text_field").value;
var text = document.createTextNode(item);
var list_element = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
list_element.appendChild(checkbox);
list_element.appendChild(text);
document.getElementById("todo-list").appendChild(list_element);
}
function reverseElement(){
var reversedElement = Array.from(document.getElementById("todo-list")).reverse()
}
Use prepend
instead of append
.
Here is the working example:
function addTask() { // Declaring Variables var item = document.getElementById("text_field").value; var list_element = document.getElementById('tasks'); var li = document.createElement("li"); li.innerText = item; list_element.prepend(li); }
<input id="text_field" /> <button onclick="addTask()">Add</button> <div> <h1>Tasks</h1> <ol id="tasks"></ol> </div>
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.