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

274
Visualizações
JQuery - Add class on click verifying ID

I'm trying to add a class to a specific element that contains a parent container with a unique ID.

I have several buttons contained in a div, and all of them are using the same classes. For some reason, I can't use only $(this), so I created a loop that adds a unique ID to the containers.

HTML

<div class='section'>
 <div class='btn-container' id='btn-1'>
  <button class='btn'></button>
 </div>
 <div class='btn-container' id='btn-2'>
  <button class='btn'></button>
 </div>
 <div class='btn-container' id='btn-3'>
  <button class='btn'></button>
 </div>
</div>

JQuery

$("button").click(function (e) {
  e.preventDefault();

  var target = $(e.target).parents(".button-container").attr("id");
  console.log(target);
  $(target).find(".btn").addClass("active");

});

I'm targeting the ID and it works, the console.log gives me back the correct info. However, for some reason, I can't add the class.

Thank you in advance for any help! (:

Edited: I'm trying to add the class active to the button that is contained in the ID.

Example: $("#btn-1 .btn").addClass("active"); but with the ID dynamically populate based on the info from the click.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Keep things simple, this should work

$(document).ready(function() {
 
  $("button").click(function (e) {
  e.preventDefault();

  $(e.target).addClass("active")

});
});
.active{
  border: 1px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='section'>
 <div class='btn-container' id='btn-1'>
  <button class='btn'>Test</button>
 </div>
 <div class='btn-container' id='btn-2'>
  <button class='btn'>Test</button>
 </div>
 <div class='btn-container' id='btn-3'>
  <button class='btn'>Test</button>
 </div>
</div>

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