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?
The definition of
is: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.
ain your code is always a single element.EDIT2: With that in mind, this would be a more efficient implementation of
present: