admin管理员组文章数量:1425221
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 thenlength===0
? – user656925 Commented Jan 31, 2013 at 22:49 -
One option perhaps worth testing is using
querySelector
instead ofgetElementsByClassName
. ThequerySelector
method returns the first result found, ornull
if none are found.document.querySelector(".myclass") === null
Plus it gives you IE8 support, wheregEBCN
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
1 Answer
Reset to default 4Yes. 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;
本文标签: javascriptHow to check for nonexistent class (getElementsByClassName)Stack Overflow
版权声明:本文标题:javascript - How to check for non-existent class? (getElementsByClassName) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745352116a2654831.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论