How do I create a functional posting history?

0
So I was trying to create a rudimentary system of "posts" with a history where all would be stored, but I realized that there was a problem that I could not solve, that the most recent posts were created below the older.

In the case, the idea was that each new "post" would overwrite the previous so that the most recent one is always at the top of the story.

Exampleofresultseeninhistory

InthecaseofthecodesallIdidwas:

CSS

div#newDivSpace{border:1pxsolid#aaa;min-height:30px;width:240px;margin-top:10px;margin-left:5px;}.post{margin-bottom:1px;padding:5px;border-bottom:1pxsolid#aaa;}

HTML

<formaction="#">
    <input type="text" id="userText">
    <button type="button" id="divGenerator" onclick="newDiv()">Criar div</button>
</form>
<div id="newDivSpace"></div>

Javascript

var input = document.getElementById("userText");
var button = document.getElementById("divGenerator");
var space = document.getElementById("newDivSpace");
var post = document.getElementsByClassName("post");

function newDiv() {
        var newDiv = document.createElement("div");
        var userInput = input.value;

        if (userInput != "") {
            newDiv.innerHTML = userInput;
            newDiv.classList.add("post");
            space.appendChild(newDiv);
            input.value = "";
        }

If you can help with the implementation of a system where the most recent message is always at the top of the history, it will be a great help.

    
asked by anonymous 08.10.2018 / 20:20

1 answer

1

Try using insertBefore

  

Syntax

var elementoInserido = elementoPai.insertBefore(novoElemento, elementoDeReferencia);

If Reference element is null, newElement will be inserted at the end of the child node list.

  • Inserted element - The node being inserted, which is newElement
  • PaP element - Parent of the newly inserted node.
  • newElement - The node to insert.
  • Reference element - The node before which the newElement will be inserted.
  

Example

<div id="elementoPai">
  <span id="elementoFilho">foo bar</span>
</div>

<script>
// Cria um novo elemento <span> vazio
var sp1 = document.createElement("span");

// Guarda a referência do elemento atraś do qual nos queremos inserir o novo elemento
var sp2 = document.getElementById("elementoFilho");
// Guarda a referência do elemento pai
var divPai = sp2.parentNode;

// Insere o novo elemento no DOM antes de sp2
divPai.insertBefore(sp1, sp2);
</script>

There is no insertAfter method. But it can be emulated by combining the insertBefore method with nextSibling.

In the previous example, sp1 could be inserted after sp2 in this way:

  

divPai.insertBefore(sp1, sp2.nextSibling);

If sp2 does not have a next node, it means that it should be the last child - sp2.nextSibling returns null , and sp1 is inserted at the end of the list of child nodes (soon after sp2).

As seen at mozilla developers

    
08.10.2018 / 20:38