简体   繁体   English

如何检查不存在的班级? (getElementsByClassName)

[英]How to check for non-existent class? (getElementsByClassName)

arr = document.getElementsByClassName(type2);  // suppose type2 is not available in the dom - class = "some_class"
// check for empty

This snippet returns 此代码段返回

[object HTMLCollection] [对象HTMLCollection]

which has a length of 0. 长度为0。

Is this the best way to check for the class not existing when getElementsByClassName is used, ie, just check for a length of 0? 这是使用getElementsByClassName时检查类是否不存在的最佳方法吗,即仅检查长度为0?

Yes. 是。 Check the length property of the returned collection. 检查返回的collection的length属性。


Since 0 is falsy, you can do this: 由于0是虚假的,因此您可以执行以下操作:

var type2 = 'some_class';
var noElementHasType2Class = ! document.getElementsByClassName(type2).length;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM