Reverse the order of elements added to DOM with JavaScript

dom, javascript

Solution

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()`

Problem

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.

Original source