1

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!

Subhajit
  • 390
  • 3
  • 18
  • When you say reference for example, it means a fiddle or code snippet, not your website – Rajesh Oct 28 '16 at 17:29
  • @Rajesh Sorry for that. I'm creating a chrome extension. Which will click element depend on user's given opinion. Could you please help me out to click the element. And I don't know ReactJS that's why I unable to create the fiddle. Thanks. – Subhajit Oct 28 '16 at 17:32
  • Also coming to question, just a suggestion, if you are using a framework or library, try to use it to max. That way, your code is consistent. So instead of trying to fetch item and trigger click, just try to call the handler. If not, try following link [Getting DOM node from React child element](http://stackoverflow.com/questions/29568721/getting-dom-node-from-react-child-element) – Rajesh Oct 28 '16 at 17:46
  • @Rajesh Thanks for the suggestion. But I'm in the same place. :( – Subhajit Oct 28 '16 at 18:16
  • Try to log element. check if you are getting correct element. If you are, it should work. If possible can you create a sample fiddle? – Rajesh Oct 29 '16 at 03:18
  • Can anyone help me out for this solution please. – Subhajit Nov 30 '16 at 12:34
  • Wow!!! Its been a month and you are still stuck. Please read my previous comment and if possible share a working sample. That way we can debug it – Rajesh Nov 30 '16 at 12:52

1 Answers1

1

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. :)

Subhajit
  • 390
  • 3
  • 18