简体   繁体   English

无法获取getElementsByClassName的长度

[英]cannot get length of getElementsByClassName

Im super confused. 我超级困惑。 I am trying to use pure JS to test if there are any elements with the class name .example on a page with a few instances of .example but I cant get consistent results... 我正在尝试使用纯JS来测试在带有.example实例的页面上是否存在任何具有类名.example的元素,但我无法获得一致的结果...

<script>
var example = document.getElementsByClassName('example');

console.log( example ); 
// gives [],
            0:div.example
            1:div.example
            2:div.example
            length:3

console.log(example.length);
// gives 0

 console.log(example[0])
// gives undefined
</script>

Is something weird going on with my computer or am I missing something? 我的计算机上发生了什么奇怪的事情吗? How should I access the length property? 我应该如何访问length属性?

I tested the console you must be defining the script before the divs. 我测试了控制台,您必须在div之前定义脚本。 here is the two scenario check your console, the first one will give undefined. 这是检查您的控制台的两种情况,第一种将给出undefined。

<script>
    var example = document.getElementsByClassName('example');

console.log( example ); 

console.log(example.length);

console.log(example[0])
</script>

<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>

this one where the script tag is defined after the elements are loaded, i am getting the consistent result 这是在元素加载后定义脚本标签的地方,我得到的结果是一致的

<div class="example"></div>
<div class="example"></div>
<div class="example"></div>
<div class="example"></div>

<script>
    var example = document.getElementsByClassName('example');

console.log( example ); 

console.log(example.length);

console.log(example[0])
</script>

javascript tags are supposed to be declared at the bottom, because it deals with manipulating of you html elements, you need to wait untill the elements are loaded, hence declare the script tags at the end, and since css must be declared right at the top, because the elements adapts their design from those css declarations! javascript标签应该在底部声明,因为它处理html元素,您需要等到元素被加载后再声明脚本标签,并且css必须在顶部声明,因为元素根据这些css声明改编其设计!

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

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