简体   繁体   中英

Object in array that exists returns undefined

I have an array from document.getElementsByClassName which has 8 elements, but whenever i want to access one the console returns undefined.

console.log(array) returns all objects from 0 - 7

console.log(array[0]) returns undefined

how is this even possible? thanks for any help!

console.log(array) :

HTMLCollection
​
0: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-综合" style="color: rgb(230, 36, 36);">
​
1: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-分类" style="color: rgb(34, 34, 34);">
​
2: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-销量" style="color: rgb(34, 34, 34);">
​
3: <li class="all-products-item price" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-价格" style="color: rgb(34, 34, 34);">
​
4: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-综合" style="color: rgb(230, 36, 36);">
​
5: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-分类" style="color: rgb(34, 34, 34);">
​
6: <li class="all-products-item" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-销量" style="color: rgb(34, 34, 34);">
​
7: <li class="all-products-item price" data-v-3d846c36="" data-spider-action-name="h5店铺首页-全部-价格" style="color: rgb(34, 34, 34);">
​
length: 8
​
<prototype>: HTMLCollectionPrototype { item: item(), namedItem: namedItem(), length: Getter, … }

document.getElementsByClassName returns a liveHTMLCollection of found elements; thus, if the DOM is changed and some of those elements are removed or have some of their classes removed, the change will also be reflected in the HTMLCollection . If you only want a static collection of elements with certain classes at a particular time, you can use document.querySelectorAll . In your case, you can use:

document.querySelectorAll(".all-products-item");

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