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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Prajeeth Emanuel
  • 647
  • 1
  • 12
  • 24

1 Answers1

1

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.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143