3

How could I specify that the items in this function should be added to the top of the list? At the moment it adds items to the bottom.

Here is the function itself:

function listFiller() {
    var list = document.getElementById('list');
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(guessedWord));
    entry.appendChild(document.createTextNode(" - "));
    entry.appendChild(document.createTextNode(seconds));
    list.appendChild(entry);
}
danrodi
  • 296
  • 1
  • 4
  • 24
  • 1
    See [this question](http://stackoverflow.com/questions/2007357/how-to-set-dom-element-as-the-first-child). – GregL Oct 14 '13 at 04:15
  • Hope helps someone. Adding items to the top of list. Add new items to before current ; new.innerHTML = willaddelements.outerHTML + currentelements.outerHTML; – Deniz Porsuk Sep 24 '18 at 11:00

2 Answers2

4
list.insertBefore(entry, list.firstChild);

See https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Phil
  • 157,677
  • 23
  • 242
  • 245
0

.appendChild() will add the element to the last, if you want to prepend any element, you can use .insertBefore()

Incase jQuery, then .prepend()

Praveen
  • 55,303
  • 33
  • 133
  • 164