bententhhousand
bententhhousand

Reputation: 33

Reverse the order of elements added to DOM with JavaScript

I am making a game in JavaScript, and need an event log. If i attack, it tells me if i hit or i miss. Here is my code:

function eventlogshow (text){
    var para = document.createElement("p");
    var node = document.createTextNode(text);
    para.appendChild(node);

    var element = document.getElementById("eventlog");
    element.appendChild(para);
}

It lists the most recent event on the bottom, with the oldest on top. How do i reverse that? I would like it to show the most recent event on the top.

Upvotes: 3

Views: 3917

Answers (2)

rink.attendant.6
rink.attendant.6

Reputation: 46218

Update (Jan 2024):

Element.prepend() is a method that is available in all mainstream browsers released 2018 and afterwards:

function eventlogshow (text){
    var para = document.createElement("p");
    var node = document.createTextNode(text);

    para.appendChild(node);

    var element = document.getElementById("eventlog");
    element.prepend(para);
}

Original answer (May 2014):

Prepend the child element instead. Since there is no prependChild() function, you need to "insert it before the first child":

function eventlogshow (text){
    var para = document.createElement("p");
    var node = document.createTextNode(text);
    
    para.appendChild(node);

    var element = document.getElementById("eventlog");
    element.insertBefore(para, element.firstChild);
}

A similar question has been asked here: How to set DOM element as first child?.

Read more about Node.firstChild and Node.insertBefore()

Upvotes: 6

Amadan
Amadan

Reputation: 198324

appendChild adds a node as a last child. You want to insert before the first node:

element.insertBefore(para, element.childNodes[0]);

Upvotes: 1

Related Questions