Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if any div has Class through alert

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");
    }
});
like image 628
TryingAtCode Avatar asked Apr 15 '15 20:04

TryingAtCode


2 Answers

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) {
        // ...
    }
});
like image 153
Josh Crozier Avatar answered Sep 23 '22 19:09

Josh Crozier


Is there some reason why directly selecting on the class: $( "div.red" ).each(...) isn't going to work?

like image 23
John Hascall Avatar answered Sep 22 '22 19:09

John Hascall