Ester
Ester

Reputation: 49

Change text to img using JavaScript

I need to change text in my html document into a small image on html load using JavaScript.

I am new to using JavaScript, so please be patient with me. Here is the code I tried:

    <body onload="stickers()">
    <span id="bonusIMG">Bonus</span>
    <script>
    function stickers() {
    document.getElementById('bonusIMG').innerHTML = <img src="http://foe.maniacal-loonies.eu/wp-content/uploads/2015/03/bonus25sq.png" alt="Bonus Added" width="25" height="25" />;
    </script>

Upvotes: 1

Views: 1103

Answers (1)

jkd
jkd

Reputation: 1045

You need to make it a string if you're going to use innerHTML and close the function with a curly brace:

<body onload="stickers()">
<span id="bonusIMG">Bonus</span>
<script>
function stickers() {
    document.getElementById('bonusIMG').innerHTML = '<img src="http://foe.maniacal-loonies.eu/wp-content/uploads/2015/03/bonus25sq.png" alt="Bonus Added" width="25" height="25" />';
}
</script>
<!--More code here-->
</body>

This example will change the text when you load the body (Using a different image):

function stickers() {
    document.getElementById('bonusIMG').innerHTML = '<img src="https://i.sstatic.net/yg5Hw.jpg?s=32&g=1" alt="Bonus Added" width="25" height="25" />';
}
<body onload="stickers()">
<span id="bonusIMG">Bonus</span>
<!--More code here-->
</body>

Upvotes: 2

Related Questions