如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
我发现这是最jQuery的方式,IMHO。扩展默认函数很简单,可以在全局扩展文件中完成。
$.fn.exist=函数(){回来此长度;};console.log($(“#yes”).exist())console.log($(“#no”).exist())<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><div id=“yes”>id=是</div>
其他回答
您可以使用:
if ($(selector).is('*')) {
// Do something
}
也许更优雅一点。
尝试测试DOM元素
if (!!$(selector)[0]) // do stuff
一个用于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.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*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');
}