Test for empty jQuery selection result

前端 未结 3 1956
余生分开走
余生分开走 2021-01-31 13:08

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.

<
相关标签:
3条回答
  • 2021-01-31 13:43

    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);
    
    0 讨论(0)
  • 2021-01-31 13:46
    if($("#something").length > 0 ){
         // Element found
    }
    else{
        // No element found
    }
    
    0 讨论(0)
  • 2021-01-31 13:54

    Use the s.length property.

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

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

    0 讨论(0)
提交回复
热议问题