Expected: Add additional class .long-ribbon to the span.ribbon.sports because the text are longer than 10 characters and it's after the .claimed ribbon.
Issue: Currently the issue is .long-ribbon classes are removed.
<div >
<span >CLAIMED</span>
<span >XXXXXXX XXXXXXX</span>
<span >XX</span>
</div>
<div >
<span >XXXX</span>
<span >XXXXXXX XXXXXXX</span>
</div>
jQuery(document).ready(function ($) {
$(".ribbons .ribbon").each(function () {
var textLength = $(this).text().length;
console.log(textLength);
if ($(".ribbons span").is(".claimed") && textLength >= 10) {
$(".ribbons > span.claimed").siblings().addClass("long-ribbon");
} else {
$(".ribbons > span.claimed").siblings().removeClass("long-ribbon");
}
});
});
I'm expecting that only the span with class sports that will be executed with .long-ribbon.
CodePudding user response:
You're better off looping through each .ribbons
div and then using find()
to see if any spans without the .claimed
class have text longer than 10 chars, and that the .claimed
class exists. Then add or remove classes accordingly:
jQuery(document).ready(function ($) {
$(".ribbons").each(function () {
if($(this).find(".ribbon:not(.claimed)").text().length > 10 && $(this).find(".ribbon").hasClass("claimed")) {
$(this).find(".ribbon:not(.claimed)").addClass("long-ribbon");
} else {
$(this).find(".ribbon:not(.claimed)").removeClass("long-ribbon");
}
});
});
.long-ribbon {
color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<span >CLAIMED</span>
<span >XXXXXXX XXXXXXX</span>
<span >XX</span>
</div>
<div >
<span >XXXX</span>
<span >XXXXXXX XXXXXXX</span>
</div>