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.
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 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.
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.
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.
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(); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With