Smith
Smith

Reputation: 3164

Is there an empty Jquery selector?

Is there a way that I can default to some kind of empty selector so that I can still call custom jQuery functions on it, but in those functions I can just check if it's valid.

I know I can check if the selector is valid before I make the function call but I would rather handle that in the functions once so that my code looks cleaner and I don't have to keep remembering to check it for additional function calls.

Say I have the following...

$.fn.Foo = function() { ... });

var $selector = someVariable != null ? $('# + someVariable') : emptySelector???

This way I could do...

$selector.Foo();

And in my function I could just check if it's valid...

$.fn.Foo = function() { 

     if ($(this) is a valid selector)
       // execute the code

});

I am new to jQuery so maybe I am thinking the wrong way. Is they any way to do this so I don't get errors saying I can't call the function on an invalid object?

Thanks.

Upvotes: 0

Views: 57

Answers (2)

Bill Criswell
Bill Criswell

Reputation: 32941

You can just check the length of what jQuery returns.

var $mightExist= $('.might-exist');
if ($mightExist.length > 0) {
  // It exists!
}

Upvotes: 0

SLaks
SLaks

Reputation: 887867

$() will return an empty jQuery object with no elements.

If your function only calls other jQuery methods like each(), you don't need any special handling; those methods will not do anything if there aren't any elements.

If you have other logic, check this.length.

Upvotes: 1

Related Questions