Is there an “exists” function for jQuery?

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

    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);
    

提交回复
热议问题