简体   繁体   中英

The second for loop in a function doesn't work

I have a function like below:

function launching() {

    let ranges = document.getElementsByClassName('range');
    liczba2 = 0;
    console.log(ranges);

    let czeks = document.getElementsByClassName('check');
    liczba = 0;
    eluwina = 0;

    for (let i = 0; i <= czeks.length; i++) {
        if (czeks[i].checked) {
            liczba ++;
            console.log(liczba);

        }
    }

    for (let n = 0; ranges.length; n++) {
        let val = ranges.getAttribute('value');
        console.log(val);
    }
}

The first for loop works fine. However the second one:

for (let n = 0; ranges.length; n++) {
        let val = ranges.getAttribute('value');
        console.log(val);
    }

Doesn't work at all. Even if there's just console log after first loop, it won't execute. I'll be grateful if anyone could help me. Thanks in advance:).

The second loop should be:

 for (let n = 0; n < ranges.length; n++) { let val = ranges[n].getAttribute('value'); console.log(val); }

In your code, if ranges.length == 0 , the loop will end immediately, since the condition ranges.length is falsey. Otherwise it will be cause an infinite loop, because the value of ranges.length doesn't change, and a non-zero value is truthy.

However, the loop will stop because ranges.getAttribute('value') will get an error. ranges is a NodeList , not a single element, and it doesn't have a getAttribute() method. You need to index it to get the current element in the iteration.

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