Christopher Thompson Christopher Thompson - 5 months ago 20
HTML Question

Javascript Replace Text With HTML

I'm doing some javascript replacement testing and have hit a wall.

The below code will replace the E10 but leave E0 alone while the E10 replacement line is present. I wish to eventually build this all the way up to E100 and then do the same for D0-100, C0-100, all the way to A and eventually S. I have pre-made graphics for all of it (Re-colored for each letter). However I can't seem to get it to function properly.

Anyone know how to make it replace each one and not just whichever one is loaded last?

<body onload="myFunction()">

E50 E30 E10 <br>

E60 E40 E0

</body>


<script>
function myFunction() {
document.body.innerHTML = document.body.innerHTML.replace(/E0/g, '<img src="http://s31.postimg.org/5riz5vn0b/Zero.png"/>');
}
</script>

<script>
function myFunction() {
document.body.innerHTML = document.body.innerHTML.replace(/E10/g, '<img src="http://s31.postimg.org/6wm82qo8r/ten.png"/>');
}
</script>


Any and all help would be appreciated.

Answer

Call the function once and add both replaces in it: https://jsfiddle.net/rx3x75rk/

function myFunction() {
    document.body.innerHTML = document.body.innerHTML.replace(/E0/g, '<img src="http://s31.postimg.org/5riz5vn0b/Zero.png"/>');
    document.body.innerHTML = document.body.innerHTML.replace(/E10/g, '<img src="http://s31.postimg.org/6wm82qo8r/ten.png"/>');
}
Comments