Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger click event using JavaScript on querySelectorAll [duplicate]

In jQuery i have the following code

$("li#credit").trigger('click'); 

This code triggers the click event only on li that has id credit.

Now to do this using JavaScript

document.querySelectorAll("li#credit").click(); 

I am getting the error:

click() is not a function

The page I am working have multiple elements with id "credit", I need to trigger a click event only on <li> that has id credit.

like image 588
Jagan K Avatar asked Jul 22 '15 17:07

Jagan K


People also ask

How can I trigger a JavaScript event click?

Trigger Click Event in JavaScript Using click() An element receives the click event when pressed, and a key is released on the pointing device (eg, the left mouse button) while the pointer is within the element. click() is triggered after the down and up mouse events are triggered in that order.

How do you click using querySelector?

How it works. First, select the button with the id btn by using the querySelector() method. Then, define a function called display() as an event handler. Finally, register an event handler using the addEventListener() so that when users click the button, the display() function will be executed.

What does the querySelectorAll () method do in JavaScript?

querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.


2 Answers

querySelectorAll returns a NodeList object (source) and not a DOM element. A NodeList object contains DOM elements.

Your code needs to change to get the first element and then call click():

document.querySelectorAll("li#credit")[0].click(); 

If you want to trigger the .click() event to all elements you can do a for loop

for(var i = 0; i<elems.length; i++) {     elems[i].click(); } 
like image 63
Tasos K. Avatar answered Oct 12 '22 05:10

Tasos K.


I found this one is clean and simple.

Array.from(document.querySelectorAll("ali#credit")).forEach(button=>button.click()) 

from this site: https://css-tricks.com/snippets/javascript/loop-queryselectorall-matches/#comment-1602558

edit 1 Thanks to Sliavik in comment.

document.querySelectorAll("ali#credit").forEach(el=>el.click()) 

is safe to call

like image 29
fangzhzh Avatar answered Oct 12 '22 05:10

fangzhzh