I am trying to apply some CSS classes on a specific html button using JQuery. The button that I am trying to target is the 2nd button in the #left-well
div. All the buttons in my html have the class of .target
and I am using the $(".target:nth-child(2)").addClass("animated bounce")
. But upon running the script, the 2nd buttons of both the divs (#left-well
and #right-well
) get targeted.
How do I write the JQuery such that only the 2nd button in #left-well
gets the class applied to it?
Here is the code for your reference:
$(document).ready(function() {
$(".target:nth-child(2)").addClass("animated bounce");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
>Solution :
Just add #left-well
to selector like:
$(document).ready(function() {
$("#left-well .target:nth-child(2)").addClass("animated bounce");
});
.animated,.bounce{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Only change code above this line -->
<div class="container-fluid">
<h3 class="text-primary text-center">jQuery Playground</h3>
<div class="row">
<div class="col-xs-6">
<h4>#left-well</h4>
<div class="well" id="left-well">
<button class="btn btn-default target" id="target1">#target1</button>
<button class="btn btn-default target" id="target2">#target2</button>
<button class="btn btn-default target" id="target3">#target3</button>
</div>
</div>
<div class="col-xs-6">
<h4>#right-well</h4>
<div class="well" id="right-well">
<button class="btn btn-default target" id="target4">#target4</button>
<button class="btn btn-default target" id="target5">#target5</button>
<button class="btn btn-default target" id="target6">#target6</button>
</div>
</div>
</div>
</div>
Next time please look the reference: Jquery Selectors