How can I detect if a selector returns null?

前端 未结 8 1928
无人及你
无人及你 2020-11-27 09:01

What is the best way to detect if a jQuery-selector returns an empty object. If you do:

alert($(\'#notAnElement\'));

you get [object Object

8条回答
  •  [愿得一人]
    2020-11-27 09:40

    I like to do something like this:

    $.fn.exists = function(){
        return this.length > 0 ? this : false;
    }
    

    So then you can do something like this:

    var firstExistingElement = 
        $('#iDontExist').exists() ||      //<-returns false;
        $('#iExist').exists() ||          //<-gets assigned to the variable 
        $('#iExistAsWell').exists();      //<-never runs
    
    firstExistingElement.doSomething();   //<-executes on #iExist
    

    http://jsfiddle.net/vhbSG/

提交回复
热议问题