user1269625
user1269625

Reputation: 3209

Jquery if my div is empty

I have this script here

<script type="text/javascript">
$(document).ready(function () {
    if($('.subhead').is(':empty')){
        $(this).css('background-color', 'none !important');
    }

});
</script>

What I am trying to do here is say if my class .subhead is empty then changed the background color, I have multiple .subhead div in code, if I run a script like this

<script type="text/javascript">
    $(document).ready(function () {
        if($('.subhead').is(':empty')){
            alert('hi');
        }else{
            alert('hello');
        }
    });
    </script>

It will return Hello

Is what I am trying to do possible?

Upvotes: 0

Views: 92

Answers (2)

Ram
Ram

Reputation: 144659

Use :empty as selector, as you have several .subhead elements, using is doesn't do what you expect. Your code says that if all of the matched elements with class of .subhead are empty then set the background-color property of all the matched elements as none.

$('.subhead:empty').css('background-color', 'none !important');

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

The default setting of background-colour is transparent, not none. Try this:

if ($('.subhead').is(':empty')){
    $(this).css('background-color', 'transparent !important');
}

Upvotes: 5

Related Questions