Is there an “exists” function for jQuery?

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

    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)) { }
    

    Alternatively, from the FAQ:

    if ( $('#myDiv').length ) { /* Do something */ }
    

    You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

    if ( $('#myDiv')[0] ) { /* Do something */ }
    

提交回复
热议问题