Reputation: 1946
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();
});
Upvotes: 0
Views: 293
Reputation: 224913
So basically, you want to show the ones that exist? Then you don't need to :)
$('.selector1, .selector2, .selector3').show();
Upvotes: 3
Reputation: 13853
jQuery will loop through them for you.
$('.selector1, .selector2, .selector3').show();
Should work as intended.
Upvotes: 3
Reputation: 41757
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();
Upvotes: 0