最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return "True" on Empty jQuery Selector Array? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Apr 15, 2012 at 21:03 Code JunkieCode Junkie 1,3723 gold badges14 silver badges24 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 14

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;
    }
});

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.

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.");

0 is "falsy" in JavaScript.

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

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.

发布评论

评论列表(0)

  1. 暂无评论