40

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.

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
Jagan K
  • 1,057
  • 3
  • 15
  • 38
  • 1
    *"The page I am working have multiple elements with id "credit""*. That's invalid. IDs must be unique. The `querySelectorAll` may fetch them, but it's still messed up. –  Jul 22 '15 at 17:31
  • 1
    Yes, I know that's invalid, but that's the way it is for 10+ years, i don't have any control to change the html, not even to use jQuery – Jagan K Jul 23 '15 at 02:12

2 Answers2

46

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

mhrabiee
  • 805
  • 10
  • 23
fangzhzh
  • 2,172
  • 21
  • 25
  • 1
    [`forEach`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach) do exist (Except of IE browser) upon `NodeList` class. You can safely use `document.querySelectorAll("ali#credit").forEach(el=>el.click())` – Slavik Meltser Feb 19 '20 at 10:58
  • This triggers the event only once, what if I want to trigger the event again for the same element? – Naman Bansal Jul 25 '21 at 17:00
  • querySelectorAll and querying of #id are prohibited to use together, because #id can be only one on the page. Multiple elements with the same ID are prohibited. id="should_be_unique". So you can use only querySelector, but it's not right too (for other reason), right usage is getElementById, and the same ID as already existing anywhere must not be used more than once on page. Use class="instead" – Fullstack Jun 13 '23 at 16:41
38

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();
}
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
  • 1
    `document.querySelectorAll("li#credit")[0].click();` is a great & simple option which basically calls the `click()` function on the first and maybe only element in the array. – Alex Mar 19 '17 at 18:56
  • Would it be possible to add something like this `addEventListener('click'` if not how would can I call a function if clicked this way `document.querySelectorAll("li#credit")[0].click();`? – utdev Apr 13 '17 at 15:33