Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add DOM elements to beginning of parent

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!

like image 521
lampwins Avatar asked Dec 06 '22 16:12

lampwins


2 Answers

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);
like image 118
Ulad Kasach Avatar answered Dec 22 '22 08:12

Ulad Kasach


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

like image 35
Šime Vidas Avatar answered Dec 22 '22 08:12

Šime Vidas