insertBefore( )

Well, in that case, we can use the insertBefore( ) method.

var body = document.getElementsByTagName( 'body' )[0];
body.insertBefore( new_div, body.firstChild );

insertBefore( ) takes two arguments: the first is the node you want to insert, and the second is the node you want to insert it in front of. In our example, we are inserting the new div in front of the firstChild of the body element.

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.