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

273
Views
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 answers
Answer question

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 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!