Is there an “exists” function for jQuery?

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

    No need for jQuery (basic solution)

    if(document.querySelector('.a-class')) {
      // do something
    }
    

    Much more performant option below(notice lack of a dot before a-class).

    if(document.getElementsByClassName('a-class')[0]) {
      // do something
    }
    

    querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to jsperf https://jsperf.com/getelementsbyclassname-vs-queryselectorall/25

    0 讨论(0)
  • 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
        }
    );
    
    0 讨论(0)
  • 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 */ }
    
    0 讨论(0)
  • 2020-11-21 05:22

    The reason all of the previous answers require the .length parameter is that they are mostly using jquery's $() selector which has querySelectorAll behind the curtains (or they are using it directly). This method is rather slow because it needs to parse the entire DOM tree looking for all matches to that selector and populating an array with them.

    The ['length'] parameter is not needed or useful and the code will be a lot faster if you directly use document.querySelector(selector) instead, because it returns the first element it matches or null if not found.

    function elementIfExists(selector){  //named this way on purpose, see below
        return document.querySelector(selector);
    }
    /* usage: */
    var myelement = elementIfExists("#myid") || myfallbackelement;
    

    However this method leaves us with the actual object being returned; which is fine if it isn't going to be saved as variable and used repeatedly (thus keeping the reference around if we forget).

    var myel=elementIfExists("#myid");
    // now we are using a reference to the element which will linger after removal
    myel.getParentNode.removeChild(myel);
    console.log(elementIfExists("#myid")); /* null */
    console.log(myel); /* giant table lingering around detached from document */
    myel=null; /* now it can be garbage collected */
    

    In some cases this may be desired. It can be used in a for loop like this:

    /* locally scoped myel gets garbage collected even with the break; */
    for (var myel; myel = elementIfExist(sel); myel.getParentNode.removeChild(myel))
        if (myel == myblacklistedel) break;
    

    If you don't actually need the element and want to get/store just a true/false, just double not it !! It works for shoes that come untied, so why knot here?

    function elementExists(selector){
        return !!document.querySelector(selector);
    }
    /* usage: */
    var hastables = elementExists("table");  /* will be true or false */
    if (hastables){
        /* insert css style sheet for our pretty tables */
    }
    setTimeOut(function (){if (hastables && !elementExists("#mytablecss"))
                               alert("bad table layouts");},3000);
    
    0 讨论(0)
  • 2020-11-21 05:23

    You can use:

    if ($(selector).is('*')) {
      // Do something
    }
    

    A little more elegant, perhaps.

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

    You can save a few bytes by writing:

    if ($(selector)[0]) { ... }
    

    This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.

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