How do you check if a selector matches something in jQuery?

This question already has an answer here:

  • Is there an “exists” function for jQuery? 36 answers

  • As the other commenters are suggesting the most efficient way to do it seems to be:

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

    If you absolutely must have an exists() function - which will be slower- you can do:

    jQuery.fn.exists = function(){return this.length>0;}
    

    Then in your code you can use

    if ($(selector).exists()) {
        // Do something
    }
    

    As answered here


    no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

    if ( $('#someDiv').length ){
    
    }
    

    if you used:

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

    you would imply that chaining was possible when it is not.

    This would be better

    jQuery.exists = function(selector) {return ($(selector).length > 0);}
    if ($.exists(selector)) { }
    
    链接地址: http://www.djcxy.com/p/14670.html

    上一篇: 检查一个div是否存在与jquery

    下一篇: 你如何检查选择器是否匹配jQuery中的某些东西?