How to select multiple classes with the same name in JS
P粉005134685
P粉005134685 2024-03-26 17:46:43
0
2
408

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粉005134685
P粉005134685

reply all(2)
P粉652523980

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

    })
});
P粉674999420

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 %

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template