4

I have the following javascript working to insert AJAX responses into a div with id results:

document.getElementById("results").innerHTML=xmlhttp.responseText;

However, this adds all new elements after those already present. I need for the new elements to be inserted before everything else.

I know this is probably very trivial but I can't seem to find anyway to do it myself.

Thanks for any help!

lampwins
  • 910
  • 1
  • 9
  • 25
  • 4
    No, it doesn't. It replaces them. – Quentin Jan 26 '12 at 13:48
  • possible duplicate of [how insert element before anchor using javascript](http://stackoverflow.com/questions/6415819/how-insert-element-before-anchor-using-javascript) – Gordon Jan 26 '12 at 13:49
  • right now, every AJAX response is added to the div. – lampwins Jan 26 '12 at 13:50
  • And a possible duplicate of http://stackoverflow.com/questions/814564/inserting-html-elements-with-javascript – Tim Jan 26 '12 at 13:50
  • 1
    please point out why none of http://stackoverflow.com/search?q=insert+before+javascript helped answer your question – Gordon Jan 26 '12 at 13:51

3 Answers3

10

With modern js you can utilize the prepend method. Currently caniuse.com says only of IE, Edge, and OperaMini are not supported.

ParentNode.prepend(nodesToPrepend);

e.g.,

ParentNode.prepend(newDiv);

Also, it automatically converts text into a text node so you could do the following for your use case:

document.getElementById("results").prepend(xmlhttp.responseText);
Ulad Kasach
  • 9,760
  • 9
  • 54
  • 80
4

You want either this

results.insertAdjacentHTML( 'beforebegin', xmlhttp.responseText );

or this

results.insertAdjacentHTML( 'afterbegin', xmlhttp.responseText );

(the variable results of course being a reference to the DOM element)

So, the first one will insert the new content before the element itself (as a previous sibling), and the second one will insert it inside the element before any other children).

Šime Vidas
  • 173,790
  • 60
  • 275
  • 374
3

I don't remember the exact syntax, but it something like:

var newDiv = document.createElement("div");
newDiv.innerHTML=xmlhttp.responseText;
document.getElementById("results").childNodes.addAt(0,newDiv);

if you can use jQuery, it's just simple as:

$("#results").prepend(xmlhttp.responseText);
Alex Dn
  • 5,333
  • 7
  • 38
  • 77