如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
如何检查jQuery中元素的存在?
我现在的代码是:
if ($(selector).length > 0) {
// Do something
}
有没有更优雅的方式来处理这个问题?也许是插件或函数?
当前回答
是的最佳方法:
通过JQuery:
if($("selector").length){
//code in the case
}
选择器可以是元素ID或元素类
OR
如果您不想使用jQuery Library,那么可以通过使用Core JavaScript实现这一点:
通过JavaScript:
if(document.getElementById("ElementID")) {
//Do something...
}
其他回答
对于jQuery,您不需要>0,这就是您所需要的:
if ($(selector).length)
使用vanilla JS,您可以使用:
if(document.querySelector(selector))
如果要将其转换为返回bool的函数:
const exists = selector => !!document.querySelector(selector);
if(exists(selector)){
// some code
}
不需要jQuery(基本解决方案)
if(document.querySelector('.a-class')) {
// do something
}
下面的选项性能更高(注意a类前面没有点)。
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector在jQuery中使用了一个适当的匹配引擎,比如$()(sizzle),并使用了更多的计算能力,但在99%的情况下都会很好。第二个选项更加明确,并且告诉代码要做什么https://jsbench.me/65l2up3t8i
实际上不需要jQuery。使用纯JavaScript,检查以下内容更容易且语义正确:
if(document.getElementById("myElement")) {
//Do something...
}
如果出于任何原因,您不想在元素中添加id,那么您仍然可以使用任何其他JavaScript方法来访问DOM。
jQuery确实很酷,但不要让纯JavaScript被遗忘。。。
我发现if($(selector).length){}不够。当选择器为空对象{}时,它将自动中断应用程序。
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
只需检查选择器的长度,如果它大于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
}