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.

2
  • 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. Commented Jul 22, 2015 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 Commented Jul 23, 2015 at 2:12

2 Answers 2

47

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

Sign up to request clarification or add additional context in comments.

3 Comments

forEach do exist (Except of IE browser) upon NodeList class. You can safely use document.querySelectorAll("ali#credit").forEach(el=>el.click())
This triggers the event only once, what if I want to trigger the event again for the same element?
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"
41

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(); } 

2 Comments

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.
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();?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.