0

I have the following Html:

<div class="box-row">
    <div class="box c2-3">
        <div class="box-overlay"></div>
        <div class="box-letter"></div>
    </div>
    <div class="box c2-4">
        <div class="box-overlay"></div>
        <div class="box-letter"></div>
    </div>
    <div class="box c2-5">
         <div class="box-overlay"></div>
         <div class="box-letter"></div>
    </div>
    <div class="box c2-6 trr">
         <div class="box-overlay trr"></div>
         <div class="box-letter"></div>
    </div>
 </div>

I want to randomly select one of the elements with class: c2-3, c2-4, c2-5, c2-6 and trigger a click.

This is the code I have thus far:

    var map = [
        'c2-3', 'c2-4', 'c2-5', 'c2-6',
    ];

    var x = Math.floor((Math.random() * 4));
    var element = document.getElementsByClassName(map[x]);

At this point I want to trigger the click and am unsure how to do it:

 element.trigger('click'); ??
HappyCoder
  • 5,985
  • 6
  • 42
  • 73
  • 1
    `getElementsByClassName()` - note the `s` in element**s**. This method returns a *collection* of elements. You cannot call `.trigger()` or `.click()` on a collection; you must first target a specific element in the collection. – Tyler Roper Sep 25 '19 at 19:58
  • 2
    Possible duplicate of [click() command not working on document.getElementsByClassName()](https://stackoverflow.com/questions/39059088/click-command-not-working-on-document-getelementsbyclassname) – Tyler Roper Sep 25 '19 at 20:01
  • 1
    Ah, and since it is a class I am looking for, there could be multiple classes... – HappyCoder Sep 25 '19 at 20:02
  • @TylerRoper That thread actually solved my problem. I changed getElementsByClassName with querySelector and it now works. Thanks! – HappyCoder Sep 25 '19 at 20:06
  • 1
    querySelector/querySelectorAll is easier (and fun fact, has better browser support) – rlemon Sep 25 '19 at 20:06

1 Answers1

2

Use element.click(); instead of element.trigger('click'); but also, you need to either get only a single element, or loop over the returned HTMLCollection from .getElementsByClassName().

For example, to loop:

var elements = document.getElementsByClassName(map[x])
elements.forEach(element => element.click())

...Or, to get a single element (still using getElementsByClassName):

var element = document.getElementsByClassName(map[x])[0]
element.click()

Alternatively, you can use querySelector:

var element = document.querySelector(`.${map[x]}`)
element.click()
BCDeWitt
  • 4,540
  • 2
  • 21
  • 34