Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda