简体   繁体   中英

Value of variable changing over time inside function w/o reassignment

<script>
    document
            .getElementById('country')
            .addEventListener('change', function() {
                'use strict';
                var value1 = this.value;
                console.log(value1);
                var vis = document.querySelectorAll('.input-group-addon'),
                country = document.getElementsByClassName(value1);
                console.log(country.length);
                // Point One
                var i;
                if (vis !== null) {
                    for (i = 0; i < vis.length; i++)
                        vis[i].className = 'input-group-addon inv';
                    console.log(country.length);
                    // Point Two
                }
                if (country !== null) {
                    for (i = 0; i < country.length; i++) {
                        country[i].className = 'input-group-addon';
                        // Point Three
                    }
                }
            });
    </script>

This has been bothering me for a while now. I am trying to get the value of a selected value in

document.querySelectorAll('.input-group-addon')

and find matching class names in

document.getElementsByClassName(value1)

The nodelist of country is available at Point One and changes to null at Point Two.

Is there a basic logic or syntax error in my code?

and changes to null at Point Two

I assume you mean that the list is empty. The variable should not magically become null .

getElementsByClassName returns a live HTMLCollection . Meaning it will always reflect the current state of document. If you change the class name of an element, it will automatically either be added or removed from the collection.

If you don't want that, then either use querySelectorAll , which returns a collection that is not live, or convert the collection to an array .

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