Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
How to select multiple class class with same name in JS

I use PHP to dynamically render these lists that I fetched from the database, and each one has the same class, because I can't change it, it renders dynamically. I select these classes via JavaScript and create an event on click to open and close them with the hidden class.

Now I have a problem, this event works for me and reacts only for the first rendered list, but not for the others. Is there any way to do this, I tried querySelectorAll and getElementsByClassName and some other selectors but nothing worked. PHP Code:

<ul class="kartonul">
                        <?php
                         $user = get_user(); 
                         $user_id = $user['id'];
                             $query = "SELECT * FROM karton WHERE id_pacijent = $user_id";
                             $result = query($query);
                         
                             if($result->num_rows > 0) {
                                 
                                 while($row = $result->fetch_assoc()) {
                                     $karton = get_karton($user_id); 
                                     foreach($result as $karton) { 
                                      echo "<li class='likarton'>Karton " .$karton['id']." <i class='fa-solid fa-envelope'></i></li>
                                        <div  class='kartondiv hiddenRaspored'>
                                        <label class='kartonlabel'>Nalaz:</label> <br/>
                                        <p>" . $karton['nalaz'] . "</p>
                                        <label class='kartonlabel'>Dijagnoza:</label> <br/>
                                        <p>" . $karton['dijagnoza'] . "</p>
                                        <label class='kartonlabel'>Pregled:</label> <br/>
                                        <p>" . $karton['pregled'] . "</p>
                                        </div>";
                                     }
                                 }
                                }
                        ?>
                    </ul>

JavaScript Code:

let karton = document.querySelector('.likarton');
let div = document.querySelector('.kartondiv');

karton.addEventListener('click', () => {
  if (div.classList.contains('hidden')) {
    div.classList.remove('hidden');
  } else {
    div.classList.add('hidden');
  }
});

This is a template: Template enter image description here

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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


Since you are using addEventListener, you are getting the exact item being clicked as an argument into the callback.

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

And to reference the element on which the event handler was fired, you can use event.currentTarget

From that point, you can select the div and use .classList.* to modify the class list


example

let karton = document.querySelectorAll('.likarton');

for (let i = 0; i < karton.length; i++) {
  karton[i].addEventListener("click", (event) => {
    let div = document.querySelector('.kartondiv');

    if (div.classList.contains('hidden')) {
      div.classList.remove('hidden');
    } else {
      div.classList.add('hidden');
    }
  });
}

refs:

  • https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#the_value_of_this_within_the_handler
  • https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll#syntax
about 4 years ago · Juan Pablo Isaza Report

0

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

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

let kartons  = document.querySelectorAll(".abc");

kartons.forEach(el => {
    el.addEventListener("click", (event) => {
         // Something happens on click

    })
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!