This is not a Duplicate question, I spent 3 days searching here and there is no other question similar to mine!
This javascript generates random words only when called from one single div, or the first one when trying different DOM Methods to get Elements.
I've tried several options and combinations with getElementsBy ID, Tag, Name, Class, and CSS Selector.
However after several days searching and testing, I can't make it work in more than one div.
I need to use the same array as the only source for all my 36 divs, to generate random words from an onClick event on each of them.
I'm open to edit it, or completely change it.
This is what I have currently working for the first div using getElementsByClassName which I suppose should be the correct way as I need to call this script from several elements, not just one:
<div class="myFruits">First Fruit</div>
<div class="myFruits">Second Fruit</div>
<div class="myFruits">Third Fruit</div>
<script>
const fruit = document.getElementsByClassName("myFruits")[0];
const randomFruits = ["Apple","Avocado","Banana","Blueberry","Cherry","Coconut",
"Fig","Grapes","Kiwi","Lemon","Mango","Orange","Papaya","Pineapple","Raspberry",
"Strawberry","Tangerine","Watermelon"]
fruit.onclick = function() {
var randomNum = Math.floor(Math.random() * (randomFruits.length))
this.innerText = randomFruits[randomNum]
}
</script>
I've tried using:
document.getElementById("element_id")
document.getElementsByClassName("css_class_name")
document.querySelector("div.className")
document.querySelectorAll("div.classNameOne, div.classNameTwo");
document.getElementsByTagName("div")
document.getElementsByTagName("div")[0].getAttribute("class");
Also tried using indexers like [0]
for those Methods returning live HTMLCollection, but nothing works, so far.
Of course I'm not an expert, so I never managed to make it work. Having exhausted my chances of success on my own, I now turn to your kind help and wisdom.
All help is very welcome. Thanks in advance.