I'm using Jquery selector. I have two addDDetails. When we click on addDDetails, system will highlight pink on second addDDetails ( which I remark [ I want select This!!! ])
I noticed that I click on first addDDetails, system highlight pink wrongly at first addDetails. How can I click on first addDDetails, system highlight pink on second addDDetails?
Thanks.
$(".addDDetails").click(function () {
$(this).closest(".Details > div").find(".addDDetails").css("background", "pink")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="row Details" style="border-style:solid;">
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 textfield">
<div class="row">
<div class="col-lg-1 col-md-1 col-xs-1 col-sm-1 textfield">
<span class="icon icon--plus addDDetails">+</span>
</div>
<div class="col-lg-11 col-md-11 col-xs-11 col-sm-11 textfield">
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 textfield">
<div class="row">
<div class="col-lg-1 col-md-1 col-xs-1 col-sm-1 textfield">
<span class="icon icon--plus addDDetails">+ [ I want select This!!! ]</span>
</div>
<div class="col-lg-11 col-md-11 col-xs-11 col-sm-11 textfield">
</div>
</div>
</div>
</div>
You can use eq() to find the specified index element and bind the corresponding event handler.
Or you can use .index() in class selector to judge the current element index and make corresponding logic.
If the elements are siblings, you could do this:
var index = $(this).index();
If not, you can pass a selector of the set in which to look for the element.
var index = $(this).index('your selector');
e. g.
const _selector = '.addDDetails';
const _cssName = 'background-color';
$(_selector).click(function() {
const index = $(this).index(_selector);
$(_selector).css(_cssName, 'red');
if (index == 0) {
$(this).eq(index).css(_cssName, '');
} else {
$(_selector).css(_cssName, '');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="row Details" style="border-style:solid;">
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 textfield">
<div class="row">
<div class="col-lg-1 col-md-1 col-xs-1 col-sm-1 textfield">
<span class="icon icon--plus addDDetails">+</span>
</div>
<div class="col-lg-11 col-md-11 col-xs-11 col-sm-11 textfield">
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 textfield">
<div class="row">
<div class="col-lg-1 col-md-1 col-xs-1 col-sm-1 textfield">
<span class="icon icon--plus addDDetails">+ [ I want select This!!! ]</span>
</div>
<div class="col-lg-11 col-md-11 col-xs-11 col-sm-11 textfield">
</div>
</div>
</div>
</div>
Here the answer use
.children('div').eq(1)
$(".addDDetails").click(function () {
$(this).closest(".Details").children('div').eq(1).find('.addDDetails').length == 1).css("background", "pink");
});
Thanks.