Javascript DOM How to - Insert to DOM using insertBefore() in body tag








Question

We would like to know how to insert to DOM using insertBefore() in body tag.

Answer


<!DOCTYPE html>
<html>
<body>bla bla
<script type='text/javascript'>
<!--from  w ww .  j  av  a 2s .c  om-->
    var p = document.createElement("p");
    p.innerHTML = "test1";
    document.body.insertBefore(p, document.body.firstChild);

</script>
</body>
</html>

The code above is rendered as follows: