代码之家  ›  专栏  ›  技术社区  ›  davetron5000

jQuery是否有“exists”函数?

  •  3126
  • davetron5000  · 技术社区  · 17 年前

    如何在jQuery中检查元素的存在?

    我现在的代码是:

    if ($(selector).length > 0) {
        // Do something
    }
    

    有没有更优雅的方法来处理这个问题?也许是插件还是函数?

    47 回复  |  直到 7 年前
        1
  •  2229
  •   Tim Büthe    8 年前

    在JavaScript中,一切都是“真实”或“虚假”的,对于数字 0 方法 false ,其他一切 true 。所以你可以写:

    if ($(selector).length)
    

    你不需要那个 >0 部分。

        2
  •  1295
  •   vaxquis user2577497    8 年前

    对!

    jQuery.fn.exists = function(){ return this.length > 0; }
    
    if ($(selector).exists()) {
        // Do something
    }
    

    这是为了回应: Herding Code podcast with Jeff Atwood

        3
  •  347
  •   R3tep    10 年前

    如果你使用

    jQuery.fn.exists = function(){return ($(this).length > 0);}
    if ($(selector).exists()) { }
    

    你可能会暗示链接是可能的,但事实并非如此。

    这样会更好:

    jQuery.exists = function(selector) {return ($(selector).length > 0);}
    if ($.exists(selector)) { }
    

    或者, from the FAQ :

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

    您还可以使用以下内容。如果jQuery对象数组中没有值,那么获取数组中的第一个项将返回undefined。

    if ( $('#myDiv')[0] ) { /* Do something */ }
    
        4
  •  117
  •   Derek 朕會功夫    9 年前

    你可以使用这个:

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

    // if element does not exist
    if(!$('selector').length){ /* do something */ }
    
        5
  •  85
  •   Randika Vishman    6 年前

    检查是否存在的最快、最语义上自解释的方法实际上是使用plain JavaScript :

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

    它的编写时间比jQuery长度替代方法长一点,但由于它是一个原生JS方法,因此执行速度更快。

    这比自己写更好 jQuery 功能。由于@snower所述的原因,这种替代方案的速度较慢。但这也会给其他程序员留下这样的印象: exists() 函数是jQuery固有的特性。 脚本 编辑代码的其他人会/应该理解你的代码,而不会增加知识债务。

    注意: 注意前面缺少“#” element_id (因为这是普通的JS,不是 实例 ).

        6
  •  60
  •   Salman Arshad    11 年前

    您可以通过写入以下内容来节省几个字节:

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

    这是有效的,因为每个jQuery对象也伪装成数组,所以我们可以使用数组解引用运算符从 阵列 .它返回 undefined 如果指定索引处没有项目。

        7
  •  55
  •   Devon    16 年前

    您可以使用:

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

    A. 小的 也许更优雅。

        8
  •  55
  •   community wiki 22 revs, 6 users 64% SpYk3HH    9 年前

    此插件可用于 if 声明类 if ($(ele).exist()) { /* DO WORK */ } 或者使用回叫。

    插件

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

    您可以指定一个或两个回调。如果元素存在,第一个将触发,如果元素存在则第二个将触发 存在。但是,如果你选择只传递一个函数,它只会在元素存在时触发。因此,如果所选元素发生以下情况,则链将死亡 存在。当然,如果它确实存在,第一个函数将启动,链将继续。

    请记住,使用 回调变量有助于保持可链接性 返回元素,您可以像使用任何其他jQuery方法一样继续链接命令!

    示例用途

    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    */
        }
    })
    
        9
  •  51
  •   Alireza    6 年前

    我看到这里的大多数答案是 不准确 正如他们应该做的那样,他们检查元素长度,它可以是 好的 在许多情况下,但是 不是100% ,想象一下,如果数字传递给函数,那么我原型化了一个函数,它检查所有条件并返回应该的答案:

    $.fn.exists = $.fn.exists || function() { 
      return !!(this.length && (this[0] instanceof HTMLDocument || this[0] instanceof HTMLElement)); 
    }
    

    这将检查长度和类型,现在你可以这样检查:

    $(1980).exists(); //return false
    $([1,2,3]).exists(); //return false
    $({name: 'stackoverflow', url: 'http://www.stackoverflow.com'}).exists(); //return false
    $([{nodeName: 'foo'}]).exists() // returns false
    $('div').exists(); //return true
    $('.header').exists(); //return true
    $(document).exists(); //return true
    $('body').exists(); //return true
    
        10
  •  49
  •   Peter Mortensen icecrime    12 年前

    其实并不需要jQuery。使用纯JavaScript,检查以下内容更容易,语义也更正确:

    if(document.getElementById("myElement")) {
        //Do something...
    }
    

    如果出于任何原因你不想给元素添加id,你仍然可以使用任何其他旨在访问DOM的JavaScript方法。

    jQuery真的很酷,但不要让纯JavaScript被遗忘。..

        11
  •  44
  •   Bellash    9 年前

    你可以用这个:

    jQuery.fn.extend({
        exists: function() { return this.length }
    });
    
    if($(selector).exists()){/*do something*/}
    
        12
  •  38
  •   technosaurus    11 年前

    前面的所有答案都需要 .length 参数是他们大多使用jquery $() 选择器,在窗帘后面有querySelectorAll(或者他们直接使用它)。此方法相当慢,因为它需要解析整个DOM树以查找 所有 与该选择器匹配,并用它们填充数组。

    ['length']参数不是必需的或有用的,如果你直接使用,代码会快得多 document.querySelector(selector) 相反,因为它返回匹配的第一个元素,如果找不到,则返回null。

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

    然而,这种方法只返回实际的对象;如果它不会被保存为变量并重复使用(从而在我们忘记的情况下保留引用),这很好。

    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 */
    

    在某些情况下,这可能是可取的。它可以在for循环中使用,如下所示:

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

    如果你实际上不需要这个元素,只想获取/存储一个true/false,那就加倍不要!!它适用于解开的鞋子,为什么要在这里打结?

    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);
    
        13
  •  33
  •   Oleg    13 年前

    $.contains() 你想要什么?

    jQuery.contains( container, contained )

    这个 $.callens() 如果第二个参数提供的DOM元素是第一个参数提供DOM元素的后代,则该方法返回true,无论它是直接子元素还是嵌套得更深。否则,它将返回false。仅支持元素节点;如果第二个参数是文本或评论节点, $.callens() 将返回false。

    笔记 :第一个参数必须是DOM元素,而不是jQuery对象或纯JavaScript对象。

        14
  •  32
  •   Anurag Deokar    9 年前

    您可以在java脚本中使用length检查元素是否存在。 如果长度大于零,则元素存在;如果长度为零,则 元素不存在

    // These by Id
    if ($("#elementid").length > 0) {
      // Element is Present
    } else {
      // Element is not Present
    }
    
    // These by Class
    if ($(".elementClass").length > 0) {
      // Element is Present
    } else {
      // Element is not Present
    }
    
        15
  •  32
  •   Mohammad DefenestrationDay    6 年前

    我找到了 if ($(selector).length) {} 不足。当以下情况发生时,它会悄无声息地破坏你的应用程序 selector 是一个空对象 {} .

    var $target = $({});        
    console.log($target, $target.length);
    
    // Console output:
    // -------------------------------------
    // [▼ Object              ] 1
    //    ► __proto__: Object
    

    我唯一的建议是对以下内容进行额外检查 {} .

    if ($.isEmptyObject(selector) || !$(selector).length) {
        throw new Error('Unable to work with the given selector.');
    }
    

    我仍在寻找更好的解决方案,因为这个有点重。

    编辑: 警告! 这在IE中不起作用 选择器 是一个字符串。

    $.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
    
        16
  •  29
  •   Palec    8 年前

    Checking for existence of an element 在jQuery官方网站上整齐地记录了!

    使用 .length 您返回的jQuery集合的属性 选择器:

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

    请注意,并不总是需要测试元素是否存在。 以下代码将显示元素(如果存在),但不执行任何操作 (无错误)如果没有:

    $("#myDiv").show();
    
        17
  •  26
  •   SJG    13 年前

    这与所有答案非常相似,但为什么不使用 ! 运算符两次,这样你就可以得到一个布尔值:

    jQuery.fn.exists = function(){return !!this.length};
    
    if ($(selector).exists()) {
        // the element exists, now what?...
    }
    
        18
  •  26
  •   Santiago Hernández    10 年前

    不需要jQuery(基本解决方案)

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

    下面有更高性能的选项(注意前面缺少一个点 a-class ).

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

    querySelector 使用适当的匹配引擎,如 $() (嘶嘶声)在jQuery中使用,并使用更多的计算能力,但在99%的情况下会做得很好。第二个选项更明确,告诉代码应该做什么 https://jsbench.me/65l2up3t8i

        19
  •  24
  •   guest271314    10 年前
    $(selector).length && //Do something
    
        20
  •  23
  •   Community CDub    8 年前

    尝试测试 DOM 要素

    if (!!$(selector)[0]) // do stuff
    
        21
  •  22
  •   Sanu Uthaiah Bollera    9 年前

    灵感来自 hiway's answer 我提出了以下建议:

    $.fn.exists = function() {
        return $.contains( document.documentElement, this[0] );
    }
    

    jQuery.contains 获取两个DOM元素,并检查第一个元素是否包含第二个元素。

    使用 document.documentElement 因为第一个参数满足了 exists 方法,当我们只想应用它来检查当前文档中元素的存在时。

    下面,我整理了一段比较 jQuery.exists() 反对 $(sel)[0] $(sel).length 两者都会回归的方法 truthy 值为 $(4) 与…同时 $(4).exists() 返回 false 在以下背景下 检查是否存在 对于DOM中的一个元素,这似乎是 期望的结果 .

    $.fn.exists = function() {
        return $.contains(document.documentElement, this[0]); 
      }
      
      var testFuncs = [
        function(jq) { return !!jq[0]; },
        function(jq) { return !!jq.length; },
        function(jq) { return jq.exists(); },
      ];
        
      var inputs = [
        ["$()",$()],
        ["$(4)",$(4)],
        ["$('#idoexist')",$('#idoexist')],
        ["$('#idontexist')",$('#idontexist')]
      ];
      
      for( var i = 0, l = inputs.length, tr, input; i < l; i++ ) {
        input = inputs[i][1];
        tr = "<tr><td>" + inputs[i][0] + "</td><td>"
              + testFuncs[0](input) + "</td><td>"
              + testFuncs[1](input) + "</td><td>"
              + testFuncs[2](input) + "</td></tr>";
        $("table").append(tr);
      }
    td { border: 1px solid black }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="idoexist">#idoexist</div>
    <table style>
    <tr>
      <td>Input</td><td>!!$(sel)[0]</td><td>!!$(sel).length</td><td>$(sel).exists()</td>
    </tr>
    </table>
    <script>
      
      $.fn.exists = function() {
        return $.contains(document.documentElement, this[0]); 
      }
      
    </script>
        22
  •  20
  •   Pawel    8 年前

    我只是喜欢使用普通的javascript来实现这一点。

    function isExists(selector){
      return document.querySelectorAll(selector).length>0;
    }
    
        23
  •  19
  •   Eternal1    10 年前

    我偶然发现了这个问题,我想分享一段我目前使用的代码:

    $.fn.exists = function(callback) {
        var self = this;
        var wrapper = (function(){
                function notExists () {}
    
                notExists.prototype.otherwise = function(fallback){
                    if (!self.length) {                    
                        fallback.call();
                    }
                };
    
                return new notExists;
            })();
    
        if(self.length) {
            callback.call();    
        }
    
        return wrapper;
    }
    

    现在我可以写这样的代码了-

    $("#elem").exists(function(){
        alert ("it exists");
    }).otherwise(function(){
        alert ("it doesn't exist");
    });
    

    它可能看起来有很多代码,但当用CoffeeScript编写时,它很小:

    $.fn.exists = (callback) ->
        exists = @length
        callback.call() if exists        
        new class
           otherwise: (fallback) ->            
                fallback.call() if not exists
    
        24
  •  18
  •   jcreamer898    13 年前

    我有一个案例,我想看看一个对象是否存在于另一个对象内部,所以我在第一个答案中添加了一些东西来检查选择器内部的选择器。。

    // Checks if an object exists.
    // Usage:
    //
    //     $(selector).exists()
    //
    // Or:
    // 
    //     $(selector).exists(anotherSelector);
    jQuery.fn.exists = function(selector) {
        return selector ? this.find(selector).length : this.length;
    };
    
        25
  •  17
  •   MAX POWER    11 年前

    怎么样:

    function exists(selector) {
        return $(selector).length;
    }
    
    if (exists(selector)) {
        // do something
    }
    

    它非常简洁,使您无需将选择器括起来 $() 每一次。

        26
  •  13
  •   andy_314    13 年前

    我使用这个:

        $.fn.ifExists = function(fn) {
          if (this.length) {
            $(fn(this));
          }
        };
        $("#element").ifExists( 
          function($this){
            $this.addClass('someClass').animate({marginTop:20},function(){alert('ok')});               
          }
        ); 
    

    仅当jQuery元素存在时执行链- http://jsfiddle.net/andres_314/vbNM3/2/

        27
  •  13
  •   Hydrothermal    6 年前

    $("selector" )返回一个对象,该对象具有 length 财产。如果选择器找到任何元素,它们将被包含在对象中。因此,如果你检查它的长度,你可以看到是否存在任何元素。在JavaScript中 0 == false ,所以如果你不明白 0 你的代码将运行。

    if($("selector").length){
       //code in the case
    } 
    
        28
  •  12
  •   ducdhm    9 年前

    这是我最喜欢的 exist jQuery中的方法

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

    以及在选择器不存在时支持回调的其他版本

    $.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);
                }
            }
        });
    };
    

    例子:

    $('#foo .bar').exist(
        function () {
            // Stuff when '#foo .bar' exists
        },
        function () {
            // Stuff when '#foo .bar' does not exist
        }
    );
    
        29
  •  10
  •   Andrei Todorut    8 年前

    你不必检查它是否大于 0 喜欢 $(selector).length > 0 , $(selector).length 这是一种足够优雅的方式来检查元素的存在。我认为仅仅为此编写一个函数是不值得的,如果你想做更多额外的事情,那么是的。

    if($(selector).length){
      // true if length is not 0
    } else {
      // false if length is 0
    }
    
        30
  •  8
  •   sth    15 年前

    以下是不同情况的完整示例,以及使用direct-if检查元素是否存在的方法。jQuery选择器可能会也可能不会工作,因为它返回数组或元素。

    var a = null;
    
    var b = []
    
    var c = undefined ;
    
    if(a) { console.log(" a exist")} else { console.log("a doesn't exit")}
    // output: a doesn't exit
    
    if(b) { console.log(" b exist")} else { console.log("b doesn't exit")}
    // output: b exist
    
    if(c) { console.log(" c exist")} else { console.log("c doesn't exit")}
    // output: c doesn't exit
    

    最终解决方案

    if($("#xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
    //output : xusyxxs doesnn't exist
    
    if($(".xysyxxs").length){ console.log("xusyxxs exist")} else { console.log("xusyxxs doesnn't exist") }
        //output : xusyxxs doesnn't exist
    

    录音样带

    console.log("existing id", $('#id-1').length)
    console.log("non existing id", $('#id-2').length)
    
    console.log("existing class single instance", $('.cls-1').length)
    console.log("existing class multiple instance", $('.cls-2').length)
    console.log("non existing class", $('.cls-3').length)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="id-1">
      <div class="cls-1 cls-2"></div>
      <div class="cls-2"></div>
    </div>