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.
dispatchEventis a DOM method, not a jQuery method.triggermethod that's similar todispatchEvent.trigger?