If any div has a class via alert

So, I have this jQuery function that checks if a particular div has a corresponding β€œred” class. However, I want to know how I can do this so that it checks mutliple Divs not only div "# Drop1".

I have 4 Divs in total from # Drop1 to # Drop4.

I want to make it work so that it checks all 4 Divs for the "red" class, and if any div has this class, display a warning message.

I looked around and did not seem to find a specific answer.

$("Button").click(function(){ if ( $("#Drop1").hasClass("red") ) { alert("one of your Divs has the class red"); } }); 
+5
source share
2 answers

Since each id attribute starts with 'Drop', you can use the attribute selector [id^='Drop'] :

 $("button").click(function(){ if ($("[id^='Drop']").hasClass("red")) { // ... } }); 

Or you can simply combine the attribute selector with the class selector and check the .length property:

 $("button").click(function(){ if ($("[id^='Drop'].red").length) { // ... } }); 
+7
source

Is there any reason why the class is directly selected: $( "div.red" ).each(...) will not work?

+1
source

All Articles