Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda