Javascript Element How to - Insert an image before a TEXT_NODE using HTML DOM








Question

We would like to know how to insert an image before a TEXT_NODE using HTML DOM.

Answer


<!DOCTYPE html>
<html>
<body>
  <p>This is a TEXT_NODE</p>
<script type='text/javascript'>
        var textNode = document.querySelector("p").firstChild;
        var img = document.createElement("img");
        img.src = "http://www.java2s.com/style/download.png";
        textNode.parentNode.insertBefore(img, textNode);  
<!--from   w  w w.  j av  a  2s .c  om-->
</script>
</body>
</html>

The code above is rendered as follows: