Replace text with image HTML | Example Using JavaScript

Use regular expression and innerHTML to Replace text with an image in HTML. A regular expression is based on what the text wants to replace.

Example how to replace the text with image html

HTML example code of Replace Text with Image using JavaScript (getElementsByClass or getElementsByID ).

Steps:

  • Use id for the text element
  • Function for the whole thing immediately execute
  • Use getElementsByClassName or idName
  • Loop through them
  • Operate on the innerHTML of each element.
<!DOCTYPE html>
<html>
<body>

    <p class="attr-value">Brand Name</p>


</body>
<script type="text/javascript">
    (function() {
        var list, index, element, filename;
        list = document.getElementsByClassName('attr-value');
        for (index = 0; index < list.length; ++index) {
            element = list[index];
            filename = element.innerHTML.toLowerCase().replace(/ /g, '-').replace(/([^0-9a-z-])/g,'');
            element.innerHTML = "<img src='abc.png'/>";
        }
    })();
</script>
</html>

Output:

replace text with image html JavaScript

Note: The above script tag will need to be placed after all of the elements you want to process in the HTML file.

Do comment if you have any better examples or have suggestions or doubts on this topic.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.