Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading