Is there an “exists” function for jQuery?

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

    I see most of the answers here are not accurate as they should be, they check element length, it can be OK in many cases, but not 100%, imagine if number pass to the function instead, so I prototype a function which check all conditions and return the answer as it should be:

    $.fn.exists = $.fn.exists || function() { 
      return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
    }
    

    This will check both length and type, Now you can check it this way:

    $(1980).exists(); //return false
    $([1,2,3]).exists(); //return false
    $({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
    $([{nodeName: 'foo'}]).exists() // returns false
    $('div').exists(); //return true
    $('.header').exists(); //return true
    $(document).exists(); //return true
    $('body').exists(); //return true
    

提交回复
热议问题