javascript - How to check for non-existent class? (getElementsByClassName) - Stack Overflow

arr = document.getElementsByClassName(type2); suppose type2 is not available in the dom - class = &

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

This snippet returns

[object HTMLCollection]

which has a length of 0.

Is this the best way to check for the class not existing when getElementsByClassName is used, i.e., just check for a length of 0?

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

This snippet returns

[object HTMLCollection]

which has a length of 0.

Is this the best way to check for the class not existing when getElementsByClassName is used, i.e., just check for a length of 0?

Share Improve this question asked Jan 31, 2013 at 22:42 user656925user656925 13
  • 1 Do you mean that the variable type2 is undefined? Or did you mean to pass the string 'type2', and that there simply are no elements with that class? And why are you concerned that checking .length === 0 is not optimal? – Matt Ball Commented Jan 31, 2013 at 22:44
  • I take it that !length is more efficient then length===0? – user656925 Commented Jan 31, 2013 at 22:49
  • One option perhaps worth testing is using querySelector instead of getElementsByClassName. The querySelector method returns the first result found, or null if none are found. document.querySelector(".myclass") === null Plus it gives you IE8 support, where gEBCN is unsupported. – the system Commented Jan 31, 2013 at 23:06
  • ...and keep in mind that gEBCN returns a "live" Node List, which makes accessing the .length more expensive. – the system Commented Jan 31, 2013 at 23:08
  • that has better patibility as well. IE8 supports it for those who care - developer.mozilla/en-US/docs/DOM/Document.querySelector – user656925 Commented Jan 31, 2013 at 23:08
 |  Show 8 more ments

1 Answer 1

Reset to default 4

Yes. Check the length property of the returned collection.


Since 0 is falsy, you can do this:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745352117a4623896.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信