Reputation: 377
The problem I have is some divs with same class but different id like this and I have another .icon
class that I want to compare the id with the ids of the box classes:
<div class="box" id="first" data-marker="first">
</div>
<div class="box" id="second" data-marker="second">
</div>
<div class="box" id="third" data-marker="third">
</div>
<div class="icon" id="first">
</div>
<div class="icon" id="second">
</div>
and I wrote a jQuery like this
$('.icon').on('click', function () {
if($(this).attr("id") == $(".box").attr("data-marker")){
value= $(this).attr("id");
console.log("#" + value);
$("#" + value ).addClass('active');
}else{
}
});
The problem is the if tag only checks the first box class for example if u click on icon class with the id of "second" it does not check other box and it only checks the box with the id of #first or better to say the first box, and thats all
Upvotes: 0
Views: 33
Reputation: 30893
If you want to use .data()
or the data
attribute, consider this code.
$('.icon').on('click', function(e) {
$("#" + $(this).data("rel")).toggleClass('active');
});
.box {
width: 200px;
height: 100px;
border: 1px solid #CCC;
background: #EEE;
}
.box.active {
border: 1px solid #2F2;
}
.icon {
width: 20px;
height: 20px;
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="box-1"></div>
<div class="box" id="box-2"></div>
<div class="box" id="box-3"></div>
<div class="icon" id="icon-1" data-rel="box-1"></div>
<div class="icon" id="icon-2" data-rel="box-2"></div>
The .toggleClass()
can be very helpful for this type of activity.
See More:
Upvotes: 1