Is there an “exists” function for jQuery?

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

    The fastest and most semantically self explaining way to check for existence is actually by using plain JavaScript:

    if (document.getElementById('element_id')) {
        // Do something
    }
    

    It is a bit longer to write than the jQuery length alternative, but executes faster since it is a native JS method.

    And it is better than the alternative of writing your own jQuery function. That alternative is slower, for the reasons @snover stated. But it would also give other programmers the impression that the exists() function is something inherent to jQuery. JavaScript would/should be understood by others editing your code, without increased knowledge debt.

    NB: Notice the lack of an '#' before the element_id (since this is plain JS, not jQuery).

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

    Checking for existence of an element is documented neatly in the official jQuery website itself!

    Use the .length property of the jQuery collection returned by your selector:

    if ($("#myDiv").length) {
        $("#myDiv").show();
    }
    

    Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:

    $("#myDiv").show();
    
    0 讨论(0)
  • 2020-11-21 05:05

    You can use this:

    // if element exists
    if($('selector').length){ /* do something */ }
    

    // if element does not exist
    if(!$('selector').length){ /* do something */ }
    
    0 讨论(0)
  • 2020-11-21 05:07

    This plugin can be used in an if statement like if ($(ele).exist()) { /* DO WORK */ } or using a callback.

    Plugin

    ;;(function($) {
        if (!$.exist) {
            $.extend({
                exist: function() {
                    var ele, cbmExist, cbmNotExist;
                    if (arguments.length) {
                        for (x in arguments) {
                            switch (typeof arguments[x]) {
                                case 'function':
                                    if (typeof cbmExist == "undefined") cbmExist = arguments[x];
                                    else cbmNotExist = arguments[x];
                                    break;
                                case 'object':
                                    if (arguments[x] instanceof jQuery) ele = arguments[x];
                                    else {
                                        var obj = arguments[x];
                                        for (y in obj) {
                                            if (typeof obj[y] == 'function') {
                                                if (typeof cbmExist == "undefined") cbmExist = obj[y];
                                                else cbmNotExist = obj[y];
                                            }
                                            if (typeof obj[y] == 'object' && obj[y] instanceof jQuery) ele = obj[y];
                                            if (typeof obj[y] == 'string') ele = $(obj[y]);
                                        }
                                    }
                                    break;
                                case 'string':
                                    ele = $(arguments[x]);
                                    break;
                            }
                        }
                    }
    
                    if (typeof cbmExist == 'function') {
                        var exist =  ele.length > 0 ? true : false;
                        if (exist) {
                            return ele.each(function(i) { cbmExist.apply(this, [exist, ele, i]); });
                        }
                        else if (typeof cbmNotExist == 'function') {
                            cbmNotExist.apply(ele, [exist, ele]);
                            return ele;
                        }
                        else {
                            if (ele.length <= 1) return ele.length > 0 ? true : false;
                            else return ele.length;
                        }
                    }
                    else {
                        if (ele.length <= 1) return ele.length > 0 ? true : false;
                        else return ele.length;
                    }
    
                    return false;
                }
            });
            $.fn.extend({
                exist: function() {
                    var args = [$(this)];
                    if (arguments.length) for (x in arguments) args.push(arguments[x]);
                    return $.exist.apply($, args);
                }
            });
        }
    })(jQuery);
    

    jsFiddle

    You may specify one or two callbacks. The first one will fire if the element exists, the second one will fire if the element does not exist. However, if you choose to pass only one function, it will only fire when the element exists. Thus, the chain will die if the selected element does not exist. Of course, if it does exist, the first function will fire and the chain will continue.

    Keep in mind that using the callback variant helps maintain chainability – the element is returned and you can continue chaining commands as with any other jQuery method!

    Example Uses

    if ($.exist('#eleID')) {    /*    DO WORK    */ }        //    param as STRING
    if ($.exist($('#eleID'))) { /*    DO WORK    */ }        //    param as jQuery OBJECT
    if ($('#eleID').exist()) {  /*    DO WORK    */ }        //    enduced on jQuery OBJECT
    
    $.exist('#eleID', function() {            //    param is STRING && CALLBACK METHOD
        /*    DO WORK    */
        /*    This will ONLY fire if the element EXIST    */
    }, function() {            //    param is STRING && CALLBACK METHOD
        /*    DO WORK    */
        /*    This will ONLY fire if the element DOES NOT EXIST    */
    })
    
    $('#eleID').exist(function() {            //    enduced on jQuery OBJECT with CALLBACK METHOD
        /*    DO WORK    */
        /*    This will ONLY fire if the element EXIST    */
    })
    
    $.exist({                        //    param is OBJECT containing 2 key|value pairs: element = STRING, callback = METHOD
        element: '#eleID',
        callback: function() {
            /*    DO WORK    */
            /*    This will ONLY fire if the element EXIST    */
        }
    })
    
    0 讨论(0)
  • 2020-11-21 05:07

    You could use this:

    jQuery.fn.extend({
        exists: function() { return this.length }
    });
    
    if($(selector).exists()){/*do something*/}
    
    0 讨论(0)
  • 2020-11-21 05:08

    In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 means false, everything else true. So you could write:

    if ($(selector).length)
    

    You don't need that >0 part.

    0 讨论(0)
提交回复
热议问题