如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
将querySelectorAll与forEach一起使用,无需if和额外赋值:
document.querySelectorAll('.my-element').forEach((element) => {
element.classList.add('new-class');
});
与以下内容相反:
const myElement = document.querySelector('.my-element');
if (myElement) {
element.classList.add('new-class');
}
其他回答
if ( $('#myDiv').size() > 0 ) { //do something }
size()统计选择器返回的元素数
这与所有答案非常相似,但为什么不使用!运算符两次,这样可以得到布尔值:
jQuery.fn.exists = function(){return !!this.length};
if ($(selector).exists()) {
// the element exists, now what?...
}
实际上不需要jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。
jQuery确实很酷,但不要让纯JavaScript被遗忘。。。
你可以使用这个:
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something*/}
我偶然发现了这个问题,我想分享一段我目前使用的代码:
$.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