简体   繁体   中英

How to iterate through HTMLCollection in Javascript/Babel

I am trying to set up a website using webpack and Babel. I am trying assign an "onclick" event to all of items inside of a table using jQuery. I am selecting all "clickable-row" table row items using getElementsByClassName which returns an HTMLCollection but when calling .length of it, it returns 0. Printing out the collection to console shows that there are items inside of it. Which leads me to thinking it's a Babel problem.

I tried converting it to an Array - the array is empty. Tried document.querySelectorAll(); which returns empty NodeList and the ... operator, tried using .forEach() and tried using HTMLCollection.prototype.forEach = Array.prototype.forEach; none of which lead anywhere.

Here is the code I'm using:

$('document').ready(getTableRows);

function getTableRows() {
    let tableRows = document.getElementsByClassName("clickable-row");
    console.log(tableRows);
    console.log("Length of this collection = " + tableRows.length);
    let array = Array.from(tableRows);
    console.log("Converted to array");
    console.log(array);
}

Here is the result returned by console in google chrome:

HTMLCollection []
    0: tr.clickable-row
    1: tr.clickable-row
    2: tr.clickable-row
    3: tr.clickable-row
    4: tr.clickable-row
    5: tr.clickable-row
    6: tr.clickable-row
    7: tr.clickable-row
    8: tr.clickable-row
    9: tr.clickable-row
    length: 10
    __proto__: HTMLCollection

Length of this collection = 0

Converted to array
[]
    length: 0
    __proto__: Array(0)

I tried recreating the same thing in jsfiddle but it didn't cause the same behaviour which leads me to think even more it's a Babel/webpack thing. http://jsfiddle.net/h2emxdf1/2/

Sorry if I mixed things up but I am a newbie if it comes to this whole webpack thing.

Thanks to @str I realized that js executes functions asynchronously which was indeed the problem in my case. So I created a callback. Now it works as it should be.

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