简体   繁体   中英

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...

<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?

I tested the console you must be defining the script before the divs. here is the two scenario check your console, the first one will give 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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