Is there an “exists” function for jQuery?

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

    Here is my favorite exist method in jQuery

    $.fn.exist = function(callback) {
        return $(this).each(function () {
            var target = $(this);
    
            if (this.length > 0 && typeof callback === 'function') {
                callback.call(target);
            }
        });
    };
    

    and other version which supports callback when selector does not exist

    $.fn.exist = function(onExist, onNotExist) {
        return $(this).each(function() {
            var target = $(this);
    
            if (this.length > 0) {
                if (typeof onExist === 'function') {
                    onExist.call(target);
                }
            } else {
                if (typeof onNotExist === 'function') {
                    onNotExist.call(target);
                }
            }
        });
    };
    

    Example:

    $('#foo .bar').exist(
        function () {
            // Stuff when '#foo .bar' exists
        },
        function () {
            // Stuff when '#foo .bar' does not exist
        }
    );
    

提交回复
热议问题