Monday, April 16, 2012

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?





No comments:

Post a Comment