最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览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?

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;
发布评论

评论列表(0)

  1. 暂无评论