0

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.

pilchard
  • 12,414
  • 5
  • 11
  • 23
rx65m
  • 105
  • 6
  • 2
    You're only assigning the onclick to the first element retrieved by your `getElementsByClassName()` call. You'll need to iterate over the returned collection and assign a listener to all of them. – pilchard Jun 13 '21 at 21:09
  • 1
    Does this answer your question? [JS: loop through list of divs to add event by onclick?](https://stackoverflow.com/questions/54210541/js-loop-through-list-of-divs-to-add-event-by-onclick), also [Adding click event listener to elements with the same class](https://stackoverflow.com/questions/21700364/adding-click-event-listener-to-elements-with-the-same-class) – pilchard Jun 13 '21 at 21:10
  • 2
    "My code is unique therefore my question is" isn't how it works - the onclick event handlers is just a different aspect of your code to the array. Split a larger problem down into chunks, and you'll find that the individual chunks have easier to find answers. – Luke Briggs Jun 13 '21 at 21:40

2 Answers2

0

You can create a loop to add the click handler to all fruits

const allfruits = document.getElementsByClassName("myFruits");

for(let fruit of allfruits) {
    fruit.onclick = function() {
       var randomNum = Math.floor(Math.random() * (randomFruits.length))
       this.innerText = randomFruits[randomNum]
    } 
}
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
0

As @pilchard said,

You're only assigning the onclick to the first element retrieved by your getElementsByClassName() call. You'll need to iterate over the returned collection and assign a listener to all of them.

What you need to do is contain all of the elements in a parent array, and then loop through that parent array's elements using [parentarray].children as the array of child elements. You can the assign the same onclick function to each element in that array.

Since all elements you want he handler on have the same class name, you can also skip the parent element and just create a live HTMLCollection of elements using var fruitDivs = document.getElementsByClassName("myFruits"); to loop through, as @Kokodoko said.

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"]

function randomFruit() {
    var randomNum = Math.floor(Math.random() * (randomFruits.length))
    this.innerText = randomFruits[randomNum]
}
var fruitDivs = document.getElementById("fruitDiv").children;
for(var i=0; i<fruitDivs.length;i++){
  fruitDivs[i].onclick=randomFruit;
}
<div id="fruitDiv">
  <div class="myFruits">First Fruit</div>

  <div class="myFruits">Second Fruit</div>

  <div class="myFruits">Third Fruit</div>
</div>
StarshipladDev
  • 1,166
  • 4
  • 17