Skip to content
Advertisement

How do I programmatically click on an element in JavaScript?

In IE, I can just call element.click() from JavaScript – how do I accomplish the same task in Firefox? Ideally I’d like to have some JavaScript that would work equally well cross-browser, but if necessary I’ll have different per-browser JavaScript for this.

Advertisement

Answer

The document.createEvent documentation says that “The createEvent method is deprecated. Use event constructors instead.

So you should use this method instead:

var clickEvent = new MouseEvent("click", {
    "view": window,
    "bubbles": true,
    "cancelable": false
});

and fire it on an element like this:

element.dispatchEvent(clickEvent);

as shown here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement