Code Junkie
Code Junkie

Reputation: 1372

Return "True" on Empty jQuery Selector Array?

I'm working on creating a more semantic way of checking for elements with jQuery. Using $("#element").length > 0 just doesn't really feel very well worded to me, so I'm making my own selector addition for use in .is:

if($("#element").is(":present")) {
  console.log("It's aliiiveeee!!");
}

That part was easy, like this:

$.extend($.expr[':'],{
    present: function(a) {
        return $(a).length > 0;
    }
});

I want to go a step further, and make it easy to see if an element doesn't exist, using similar syntax:

$.extend($.expr[':'],{
    present: function(a) {
        return $(a).length > 0;
    },
    absent: function(a) {
        return $(a).length === 0;
    }
});

$(function() {
  if($("#element").is(":absent")) {
    console.log("He's dead, Jim.");
  }
});

But this part is surprisingly hard to do. I think it's because I'm paring down the returned elements to get a result, and paring the selector to .length === 0 is the same as asking for no elelements: it returns false no matter what.

I've tried a lot of different ways to reverse things and get this to return true when the element doesn't exist, and false if it does:

return $(a).length === 0;

return !($(a).length > 0);

if(!($(a).length > 0)) { 
  return true;
} 

if($(a).length > 0) { 
  return false;
} else {
  return true;
}

return !!($(a).length === 0);

// etc...

Is there an easy way to get this to just return true if the element doesn't exist, and false if it does?

Upvotes: 15

Views: 2888

Answers (5)

Xion
Xion

Reputation: 22770

Given that $().is() won't even run when the collection is empty, the :present selector is rather superfluous. So rather than playing with $.expr[':'], I'd go with extending $.fn to contain appropriate function, e.g.:

$.fn.extend({
    hasAny: function() {
        return this.length > 0;
    },
});

or

$.fn.extend({
    isEmpty: function() {
        return this.length == 0;
    },
});

The reason I would personally go with this approach is that selectors are typically used to check particular properties of elements (compare :checked, :enabled, :selected, :hover, etc.), not the properties of jQuery element set as a whole (e.g. .size(), .index()).

Usage would of course be similar to the following:

if ($('#element').isEmpty())
    console.log("He's dead, Jim.");

Upvotes: 2

SLaks
SLaks

Reputation: 887449

0 is "falsy" in JavaScript.

You can just return !$(a).length.

Upvotes: 1

James Montagne
James Montagne

Reputation: 78650

The definition of is:

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

The problem is that since you have no elements, it's not possible that one of your elements matches some condition. jQuery is not even calling your code because there are no elements.

EDIT: To clarify slightly, your code is being called once for every element in your object (at least until one returns true). No elements means the code is never called. a in your code is always a single element.

EDIT2: With that in mind, this would be a more efficient implementation of present:

$.extend($.expr[':'],{
    present: function(a) {
        return true;
    }
});

Upvotes: 14

The Alpha
The Alpha

Reputation: 146191

You can simply use

if(​$('element').length) // 1 or 0 will be returned

or

$.extend($.expr[':'],{
    present: function(a) {
        return $(a).length;
    }
});

if($('#element').is(':present'))
{
    // code for existence
}
else
{
    // code for non-existence
}

Example.

Upvotes: 6

Šime Vidas
Šime Vidas

Reputation: 185923

How about:

if ( !$(a)[0] ) {
    // $(a) is empty
}

So, $(a)[0] retrieves the first element in the jQuery object. If that element is null/undefined, that means that the jQuery object is empty.

Upvotes: 0

Related Questions