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

我现在的代码是:

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

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


当前回答

只需检查选择器的长度,如果它大于0,则返回true,否则返回false。

对于ID:

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}

对于类别:

 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

对于下拉列表:

if( $('#selector option').size() ) {   // use this if you are using dropdown size to check

   // it exists
}

其他回答

试试这个。

简单、简短,可在整个项目中使用:

jQuery.fn.exists=function(){return !!this[0];}; //jQuery Plugin

用法:

console.log($("element-selector").exists());

_________________________________

或更短:(当您不想定义jQuery插件时):

if(!!$("elem-selector")[0]) ...;

甚至

if($("elem-selector")[0]) ...;

对于jQuery,您不需要>0,这就是您所需要的:

if ($(selector).length)

使用vanilla JS,您可以使用:

if(document.querySelector(selector))

如果要将其转换为返回bool的函数:

const exists = selector => !!document.querySelector(selector);

if(exists(selector)){
  // some code
}

您可以使用此选项:

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

// if element does not exist
if(!$('selector').length){ /* do something */ }

受到海威回答的启发,我想到了以下几点:

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

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

当我们希望仅应用document.documentElement来检查当前文档中元素的存在时,使用document.documentsElement作为第一个参数可以实现exists方法的语义。

下面,我将jQuery.exists()与$(sel)[0]和$(sel).length方法进行了比较,这两种方法都返回了$(4)的真值,而$(4().exists)返回了假值。在检查DOM中是否存在元素的上下文中,这似乎是理想的结果。

$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}var测试功能=[函数(jq){return!!jq[0];},函数(jq){return!!jq.length;},函数(jq){return jq.exists();},];var输入=[["$()",$()],["$(4)",$(4)],[“$('#idexist')”,$('#idexist])],[“$('#idotexist')”,$('#idotexit')]];for(变量i=0,l=inputs.length,tr,input;i<l;i++){input=输入[i][1];tr=“<tr><td>”+输入[i][0]+“</td><td]”+testFuncs[0](输入)+“</td><td>”+testFuncs[1](输入)+“</td><td>”+testFuncs[2](输入)+“</td></tr>”;$(“table”).append(tr);}td{border:1px实心黑色}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div id=“idexist”>#idexist</div><表格样式><tr><td>输入</td><td>$(sel)[0]</td><td>$(sel).length</td><td>$(sel).exists()</td></tr></table><脚本>$.fn.exists=函数(){return$.contains(document.documentElement,this[0]);}</script>

检查元素的存在在jQuery官方网站中有完整的文档记录!

使用选择器:if($(“#myDiv”).length){$(“#myDiv”).show();}注意,并不总是需要测试元素是否存在。下面的代码将显示元素(如果存在),并且不做任何操作(无错误)如果没有:$(“#myDiv”).show();