Example html:
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
<div class="apple"></div>
I want to loop through the divs and filter them out if they don’t have a class of either ‘red’, ‘green’, or ‘blue’.
var onlyColorDivs = $('div').hasClass( __________ );
Is there a way to filling the blank in the previous line to accomplish this. Or am I going to have to put my list color classes in an array and do a loop?
Let me know if any clarification is needed.
All the answers are great and are appropriate. But, if you need a function like this a lot, you could also Monkey Patch the
hasClassmethod to do what you want:Then you can use it like this:
Demo on JS Bin