1

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.

4
  • You redeclare your myFunction so the first one gets removed and is never executed. Commented Jun 14, 2016 at 22:09
  • I was about to say that :) Commented Jun 14, 2016 at 22:09
  • To generalize the lesson here: <script> blocks do not have any "scope". All <script> blocks loaded by the page are basically concatenated into one big script file. Commented Jun 14, 2016 at 22:26
  • Yes, I see that now. Thank you, I learned a great deal from this. Commented Jun 14, 2016 at 23:56

1 Answer 1

1

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"/>');
}
Sign up to request clarification or add additional context in comments.

2 Comments

Quick thing, any way to have this exclude making changes to input fields? It is currently effecting the entire site, which is great. I just didn't think about it effecting textareas. xD
@ChristopherThompson yes, but I would need some samples of what you want to change

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.