Is there an “exists” function for jQuery?

前端 未结 30 3022
野性不改
野性不改 2020-11-21 04:52

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}
<         


        
30条回答
  •  野的像风
    2020-11-21 05:14

    I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

    var $target = $({});        
    console.log($target, $target.length);
    
    // Console output:
    // -------------------------------------
    // [▼ Object              ] 1
    //    ► __proto__: Object
    

    My only suggestion is to perform an additional check for {}.

    if ($.isEmptyObject(selector) || !$(selector).length) {
        throw new Error('Unable to work with the given selector.');
    }
    

    I'm still looking for a better solution though as this one is a bit heavy.

    Edit: WARNING! This doesn't work in IE when selector is a string.

    $.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
    

提交回复
热议问题