Test for empty jQuery selection result

JavascriptJquery

Javascript Problem Overview


Say I do

var s = $('#something');

and next I want to test if jQuery found #something, i.e. I want to test if s is empty.

I could use my trusty isempty() on it:

function isempty(o) {
    for ( var i in o )
        return false;
    return true;
}

Or since jQuery objects are arrays, I suppose I could test s.length.

But neither seem quite in the idiom of jQuery, not very jQueryesque. What do you suggest?

Javascript Solutions


Solution 1 - Javascript

Use the s.length property.

if(s.length == 0) {
    ...
}

[edit] size() deprecated in jquery 1.8 http://api.jquery.com/size/

Solution 2 - Javascript

if($("#something").length > 0 ){
     // Element found
}
else{
    // No element found
}

Solution 3 - Javascript

An even more jQueryesque solution for me is:

jQuery.fn.isEmpty = function(fun){ if (this.length === 0) { fun(); } return this; };

This lets me write in typical fashion:

$("#sel").fadeOut(500,afterFade).isEmpty(insteadOfFade);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser213154View Question on Stackoverflow
Solution 1 - JavascriptBilliamView Answer on Stackoverflow
Solution 2 - JavascriptMalik KhalilView Answer on Stackoverflow
Solution 3 - JavascriptDonView Answer on Stackoverflow