Javascript Element How to - Insert dynamically created div before content in a tag








Question

We would like to know how to insert dynamically created div before content in a tag.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload = function () {<!--from w  w w .  ja v  a 2s  .  co m-->
    var jselem = document.createElement("div");
    jselem.innerHTML = '<p>Some other text here</p>';
    document.body.insertBefore(jselem, document.body.firstChild);
};

</script>
</head>
<body>
<body>
  <p>Here's some text</p>
</body>
</body>
</html>

The code above is rendered as follows: