Home > other >  How to replace text with a random array element?
How to replace text with a random array element?

Time:11-22

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>

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related