最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Reverse the order of elements added to DOM with JavaScript - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 6

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

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

element.insertBefore(para, element.childNodes[0]);
发布评论

评论列表(0)

  1. 暂无评论