Is there an “exists” function for jQuery?

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

    Yes!

    jQuery.fn.exists = function(){ return this.length > 0; }
    
    if ($(selector).exists()) {
        // Do something
    }
    

    This is in response to: Herding Code podcast with Jeff Atwood

提交回复
热议问题