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.
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.
Share Improve this question edited May 20, 2014 at 1:25 rink.attendant.6 46.4k64 gold badges110 silver badges157 bronze badges asked May 20, 2014 at 1:01 bententhhousandbententhhousand 331 silver badge4 bronze badges 1- 1 You should prepend instead of append the element. – Jonathan Commented May 20, 2014 at 1:07
2 Answers
Reset to default 6Update (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()
appendChild
adds a node as a last child. You want to insert before the first node:
element.insertBefore(para, element.childNodes[0]);