HappyCoder
HappyCoder

Reputation: 6155

How to trigger a click on an element in javascript

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'); ??

Upvotes: 3

Views: 3965

Answers (2)

Marco Balestra
Marco Balestra

Reputation: 1

The getElementsByClassName() method returns an array-like object of all child elements with all the given class name(s).
I'd rather consider using querySelectorAll(), but the output is the same: in any case a node collection is returned.

Cycle on such nodes, and if you want to use a "modern" there is dispatchEvent() instead of click():

document.getElementsByClassName(map[x]).forEach( el => {
    el.dispatchEvent( new MouseEvent(
        'click',
        { view: window, bubbles: true, cancelable: true }
    ));
});

Should you want to be more precise you could replace

document.getElementsByClassName(map[x])

with:

document.querySelectorAll('div.box-row > .box.'+map[x])

Upvotes: 0

BCDeWitt
BCDeWitt

Reputation: 4773

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()

Upvotes: 5

Related Questions