Home > Back-end >  JQuery - Add class on click verifying ID
JQuery - Add class on click verifying ID

Time:12-08

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.

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related