search

Home  >  Q&A  >  body text

How to select multiple classes with the same name in JS

I am using PHP to dynamically render these lists that I get from the database, each list has the same class and since I cannot change it, it renders dynamically. I select these classes via JavaScript and create an event on click to open and close them using the hidden class.

Now I have a question, this event works for me and only for �

P粉005134685P粉005134685272 days ago409

reply all(2)I'll reply

  • P粉652523980

    P粉6525239802024-03-27 14:50:25

    You need to use querySelectorAll() instead of querySelector().

    This way you will target all elements instead of the first matching element. You should then loop through each event and add an event listener like this:

    let kartons  = document.querySelectorAll(".abc");
    
    kartons.forEach(el => {
        el.addEventListener("click", (event) => {
             // Something happens on click
    
        })
    });

    reply
    0
  • P粉674999420

    P粉6749994202024-03-27 14:10:01

    You are only selecting the first .likarton instance - this is fixed by using querySelectorAll()


    Since you are using addEventListener, you will get the exact item that was clicked as a parameter in the callback.

    The correct JavaScript to use this feature is addEventListener('click', (event) => {})

    To reference the element that triggered the event handler, you can use %

    reply
    0
  • Cancelreply