Subhajit
Subhajit

Reputation: 398

JavaScript programmatically .click() is not triggered in ReactJS element

I'm trying to click to a react JS element programmatically.

for example please check this link: Click Here

I'm unable to click to the swatch images, which will change the main product image.

I tried with this below code:

document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a').click();

document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a > span > img').click();

Both are not working. I also tried

function clickElement(el){
    var ev = document.createEvent("MouseEvent");
    ev.initMouseEvent(
        "click",
        window, null,
        false, false, false, false,
        0, null
    );
    el.dispatchEvent(ev);
}

Still the element is not changing.

Thanks!

Upvotes: 1

Views: 747

Answers (1)

Subhajit
Subhajit

Reputation: 398

I have found a solution to click on a ReactJS element from outside of the it's DOM.

var elm = document.querySelector('#product-selection-4476800 > section.np-sku-filters > div.np-circular-swatches.small > ul > li:nth-child(2) > a');

function triggerEvents(n, e){
    var ev = document.createEvent('MouseEvents');
    ev.initEvent(e, true, true);
    n.dispatchEvent(ev);
}

triggerEvents(elm, "mouseover");
triggerEvents(elm, "mousedown");
triggerEvents(elm, "click");
triggerEvents(elm, 'mouseup');

And it works as expected.

Thanks all for your time and responses. :)

Upvotes: 1

Related Questions