Is there an “exists” function for jQuery?

前端 未结 30 3093
野性不改
野性不改 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
    
    0 讨论(0)
  • 2020-11-21 05:24

    Is $.contains() what you want?

    jQuery.contains( container, contained )

    The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

    Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

    0 讨论(0)
  • 2020-11-21 05:25
    $(selector).length && //Do something
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 05:28

    this is very similar to all of the answers, but why not use the ! operator twice so you can get a boolean:

    jQuery.fn.exists = function(){return !!this.length};
    
    if ($(selector).exists()) {
        // the element exists, now what?...
    }
    
    0 讨论(0)
  • 2020-11-21 05:29

    You can check element is present or not using length in java script. If length is greater than zero then element is present if length is zero then element is not present

    // These by Id
    if ($("#elementid").length > 0) {
      // Element is Present
    } else {
      // Element is not Present
    }
    
    // These by Class
    if ($(".elementClass").length > 0) {
      // Element is Present
    } else {
      // Element is not Present
    }
    
    0 讨论(0)
提交回复
热议问题