Skip to content
Advertisement

How to replace text with a random array element?

I am trying to replace text with a random element in my array. When the user clicks on the text itself, the word should change to one of the elements in my array. I am having trouble with the function that lets me do so. I have text and wrapped span tags (named “hare”) around words that I want to be able to change. I included my code below. Any help would be appreciated.

//code below 
<script>
let C = document.getElementsByClassName("hare");
//console.log(C);
let L = C.length;
//console.log(L);
for (var i = 0; i < L; i++)
  C[i].addEventListener("Click",changeWord);

function changeWord() {
  let CC = document.getElementsByClassName("hare");
  var h = ["Rabbit", "Snake", "Human"];
  let rndWord = h[Math.floor(Math.random()*h.length)];
  //console.log(rndWord);
  for (var i = 0; i < CC.length; i++)
    CC[i].innerHTML = rndWord;

}

</script>

Advertisement

Answer

Event types are case sensitive eg
C[i].addEventListener("click",changeWord);

let C = document.getElementsByClassName("hare");
//console.log(C);
let L = C.length;
//console.log(L);
for (var i = 0; i < L; i++)
  C[i].addEventListener("click",changeWord);

function changeWord() {
  let CC = document.getElementsByClassName("hare");
  var h = ["Rabbit", "Snake", "Human"];
  let rndWord = h[Math.floor(Math.random()*h.length)];
  //console.log(rndWord);
  for (var i = 0; i < CC.length; i++)
    CC[i].innerHTML = rndWord;

}
<button class="hare">Click here</button>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement