I am attempting to add a class to a span, if a set of li’s have a specific class applied to them.
li . complete
li
li . complete
li
li . complete
etc…
span # done
I was attempting to add a class of “active” to the span if 4 of the li’s have the class “complete”
I’ve tried the following, and I can get the click event to work but not the if statement, and is this even possible or efficiient?
$(function(){
$("li").click(function(){
$(this).addClass("complete");
});
if($("li").hasClass("complete")){
$("#done").addClass("active");
};
});
Ive been digging for a way to maybe count the li.complete’s withing the dom then addClass against it but haven’t had much luck
Thanks
Your current code won’t has two problems: you’re running
immediately after binding the
click()handler, not after the button has actually been clicked. Additionally, you’re not counting the number oflis that have been made complete.One option is this, counting the number of
li‘s with the class complete each time you handle the click:You could also keep a running count as you go…
but if you ever want to be able to unselect items, this would make your code more complicated.