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 date = new Date;
var item = document.getElementById("text_field").value;
var list_element = document.getElementById('tasks');
var li = document.createElement("li");
li.innerText = item + '\t|\t' + date.toISOString();
list_element.prepend(li);
}
<input id="text_field" />
<button onclick="addTask()">Add</button>
<div>
<h1>Tasks</h1>
<ol id="tasks"></ol>
</div>