0

I'm trying to create a function to mouse click elements.

Lets consider $(element).click() out of this question's scope now, I want to create it this way:

function mouseClick() {
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true
    });

    var element = document.getElementById('elementId');
    element.dispatchEvent(event);
}

mouseClick();

The problem is:

When I try to pass elements as arguments to this function (as a jQuery object), when I'm calling it:

function mouseClick(element) {
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true
    });

    //var element = document.getElementById('elementId'); <==== I want to remove this to replace it with the arguments when I call it;
    element.dispatchEvent(event);
}

var element = $('#elementId');
mouseClick(element);

I get the console error:

Uncaught TypeError: element.dispatchEvent is not a function

But when I select the elements using getElementById it works:

var element = $('#elementId'); //<==== this doesn't work;
var element = document.getElementById('elementId'); //<==== this works;
mouseClick(element);

Why is this happening?

And how can I make the jQuery selectors way works?

Basically I want to select elements in more advanced ways beyond the ID selector, so, I think jQuery comes handy and write less.

4
  • 1
    dispatchEvent is a DOM method, not a jQuery method. Commented Sep 8, 2017 at 23:16
  • jQuery has a trigger method that's similar to dispatchEvent. Commented Sep 8, 2017 at 23:17
  • @Barmar would you please give an example for how to use the jQuery trigger? Commented Sep 8, 2017 at 23:22
  • There are examples in the documentation. Commented Sep 8, 2017 at 23:23

2 Answers 2

1

jQuery objects are not the same as DOM elements, and you generally can't call the same methods on them (there are a few cases where they have similar methods with the same name, e.g. submit() for forms). dispatchEvent() is a DOM method, not a jQuery method, so you can't call it on a jQuery object.

You can get the DOM element from a jQuery object using the get() method, so you can do:

mouseClick(element.get(0));

You can also use subscripting as a shortcut:

mouseClick(element[0]);
Sign up to request clarification or add additional context in comments.

Comments

1

The result of a jquery selector is not a DOM element, so you can't use displayEvent on it.

You can go over all the elements in your jquery selector and apply dispatch the event to every one of them:

Object.keys(element).forEach(function(key) {
    element[key].dispatchEvent(event);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.