0

Extending: https://stackoverflow.com/a/31047/235633

Is there a way I can extend this custom jQuery function to use a callback? Essentially I want to be able to have a list of selectors and detect their existence and if they exist, I need to show them.

Instead of writing a thousand if statements, I rather write one function that uses a callback and 'this'.

The guy wrote:

jQuery.fn.exists = function(){return this.length>0;}

if ($(selector).exists()) {
    // Do something
}

But I need:

$('.selector1, .selector2, .selector3').exists(function({
    $(this).show();
});
Community
  • 1
  • 1
bafromca
  • 1,906
  • 4
  • 26
  • 42

3 Answers3

3

jQuery will loop through them for you.

$('.selector1, .selector2, .selector3').show();

Should work as intended.

Andrew
  • 13,567
  • 13
  • 64
  • 80
3

So basically, you want to show the ones that exist? Then you don't need to :)

$('.selector1, .selector2, .selector3').show();
Ry-
  • 209,133
  • 54
  • 439
  • 449
0

In the general case you can use .each for this:

$('.selector1, .selector2, .selector3').each(function({
  //some work involving $(this) 
});

But in this case, show works on all matched elements anyway:

$('.selector1, .selector2, .selector3').show();
Rich O'Kelly
  • 40,274
  • 9
  • 81
  • 111