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

我现在的代码是:

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

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


当前回答

$(selector).length && //Do something

其他回答

您可以使用:

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

也许更优雅一点。

以下是jQuery中我最喜欢的exist方法

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

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

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

一个用于id和类选择器的简单实用函数。

function exist(IdOrClassName, IsId) {
  var elementExit = false;
  if (IsId) {
    elementExit = $("#" + "" + IdOrClassName + "").length ? true : false;
  } else {
    elementExit = $("." + "" + IdOrClassName + "").length ? true : false;
  }
  return elementExit;
}

像下面这样调用此函数

$(document).ready(function() {
  $("#btnCheck").click(function() {
    //address is the id so IsId is true. if address is class then need to set IsId false
    if (exist("address", true)) {
      alert("exist");
    } else {
      alert("not exist");
    }
  });
});

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

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

如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。

jQuery确实很酷,但不要让纯JavaScript被遗忘。。。