Skip to content

Replace image with text JavaScript | Example code

  • by

Use getElementsByTagName method to Replace image with text JavaScript. This method returns a live node list so every time you replace a node the list changes, so you only want to get the first node in the list and replace it.

Example of how to Replace image with text JavaScript

First, select any element you want change.

var elem = document.getElementsByTagName('body')[0];
var target = elem.innerHTML;

Then Replace it (div to p)

elem.innerHTML = target.replace(/(<div)/igm, '<p').replace(/<\/div>/igm, '</p>');

Compete HTML example code:

<!DOCTYPE html>
<html>
<body>

    <img class="attr-value" src='abc.png'/>

    <script type="text/javascript">

        var elem = document.getElementsByTagName('body')[0];
        var target = elem.innerHTML;
        
        console.log(target);

        elem.innerHTML = target.replace(/(<img)/igm, '<p').replace(/<\/img>/igm, '</p>');
    </script>
</body>

</html>

Output:

HTML Replace image with text JavaScript

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading