I have two baffling things going on,
First: Is I’m trying to use the .innerHTML to change more than just the first occurrence.
Second: Is that I’m trying to have a random word replace the .innerHTML.
I’ve only been able to change the first word let alone all plus the random is a complete fail, any help would be appreciated.
Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>
Hello <p id="p1">World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="newWorld()";
function newWorld() {
var worlds = new Array ("Pluto!", "Mars!", "Saturn!", "Earth!", "Mercury!");
var whichWorld = Math.floor(Math.random()*worlds.length);
worlds[whichWorld]();
};
</script>
IDs in HTML documents are meant to be unique. The function
getElementByIdwill only ever return 1 element, nothing more. For groups of similar elements, you want to give them all a commonclassand then usegetElementsByClassName(notice the plural Elements vs Element) – this function won’t work with IE 8 or earlier, however, so if you need to support IE you would have to dogetElementsByTagNameand then filter in only those that have the class you want.As far as the second part of the code, first you are setting the innerHTML to the actual string
newWorld()not to the return value of the function (which there is none, as you are not currently returning something from withinnewWorld) – I think you meant to dodocument.getElementById("p1").innerHTML = newWorld();. Secondly, the random part of the code is correct and should be choosing a random planet each time. The end of the code is a bit puzzling, however – what exactly are you trying to do there?worlds[whichWorld]is going to be a string (Earth!, etc.) not a callable function. Ifworldswas an array of functions then the code would work (assuming you also returned it, since you intend to set it as the innerHTML)In short, something like this would be the “proper” way to set all
<span>elements within a parent element to a random planet:And the Javascript:
And here it is in action. You are clearly new to Javascript so I encourage you to continue to try and learn the basics of it. Eventually, however, you will want to look into libraries such as jQuery which make a lot of the tediousness of writing cross-browser Javascript go away.