Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Hot to reverse the order of a html list from javascript?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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()
} 
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!