Add class to empty elements only

The problem is that I have multiple instances of .Prodotto but I would like to add the class only to the empty .Prodotto. How can I specify only the empty '.Prodotto' ? My jQuery attempt is this one:

if ($('.Prodotto').is(':empty')){
  $('.Prodotto').addClass('empty-content');
}

Upvotes: 1

Views: 750

Answers (4)

N. Ivanov
N. Ivanov

Reputation: 1823

Your question is too vague, if you give a bit more details, but I assume that you have a click event somewhere? If that is the case, assuming you have something like:

    $("body").on("click", ".Prodotto", function(){ 
    if($(this).is(":empty")){ 
            $(this).addClass("empty-content");
    }
    });

Hope this helps!

Upvotes: 0

Oliver Sartun
Oliver Sartun

Reputation: 56

This is probably what you're looking for:

$('.Prodotto').filter(':empty').addClass('empty-content');

Or even shorter:

$('.Prodotto:empty').addClass('empty-content');

In your code you're first testing if there are any empty elements with the class Prodotto, but then you query Prodotto a second time and apply the new class to all of them.

Upvotes: 2

Jamiec
Jamiec

Reputation: 136134

Generally, I think what you're trying to do is

$('.Prodotto:empty').addClass('empty-content');

But when you say the "Current .Prodotto", it implies there is something else in your code which makes it the "current" one, like having clicked on it, and if so your code is similar to your existing, except using this

$('.Prodotto').on('click',function(){
    var $this = $(this);
    if ($this.is(':empty')){
        $this.addClass('empty-content');
    }
});

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337626

You can use the :empty selector directly and remove the if statement, like this:

$('.Prodotto:empty').addClass('empty-content');

Upvotes: 3

Related Questions