I am trying to add new class to the parent class if nodes has a certain class.
$(document).ready(function() {
if ($(".row").hasClass("lock-icon")) {
$(".row .lock-icon").parent(".content-box").addClass('locked-badge');
}
});
.locked-badge {
opacity: 0.2;
cursor: not-allowed;
}
<div class="col-md-6 mb-5">
<div class="content-box">
<div class="row">
<h3>Some rank name</h3>
<div class="col">
<div class="lock-icon">
<i class="fa fa-lock">lock icon</i>
</div>
</div>
</div>
<div class="row">
<p class="badges-text">
Some rank description
</p>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
I also have tried this jQuery
$(document).ready(function(){
var $locked = $('.content-box').hasClass('lock-icon');
$($locked).each(function() {
$(this).addClass('locked-badge');
});
});
Still not working.
2
Answers
Instead of trying to locate the
parent
(s) of the element with the classlock-icon
, consider trying to find out if the parent has a child with the classlock-icon
No need to go for
.hasClass()
. Simply target that class and search for.closest()
parent – in a single line of jQuery:or, in pure JavaScript: