So i have this jQuery function that checks if a particular div has the "red" class attached to it. However i want to know how i can make it so that it checks mutliple Divs not just the "#Drop1" div.
I have 4 Divs in total from #Drop1 all the way to #Drop4.
I want to get it working so that it checks all 4 Divs for the class "red" and if any div has this class show the alert message.
I've looked around and can't seem to find a concrete answer.
$("Button").click(function(){
if ( $("#Drop1").hasClass("red") ) {
alert("one of your Divs has the class red");
}
});
Since each of the element's id
attributes start with 'Drop', you could use the attribute selector [id^='Drop']
:
$("button").click(function(){
if ($("[id^='Drop']").hasClass("red")) {
// ...
}
});
Or you could just combine the attribtue selector with a class selector and check the .length
property:
$("button").click(function(){
if ($("[id^='Drop'].red").length) {
// ...
}
});
Is there some reason why directly selecting on the class: $( "div.red" ).each(...)
isn't going to work?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With