Is there an “exists” function for jQuery?

前端 未结 30 3099
野性不改
野性不改 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:19

    I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

    // Checks if an object exists.
    // Usage:
    //
    //     $(selector).exists()
    //
    // Or:
    // 
    //     $(selector).exists(anotherSelector);
    jQuery.fn.exists = function(selector) {
        return selector ? this.find(selector).length : this.length;
    };
    

提交回复
热议问题