1

I assign the results of document.getElementsByClassName("red") to the array redElements. I then change one element from class .red to class .blue. I expected redElements to keep its original three values, but instead it now contains only the two elements that are still red. This is surprising. What's the reason for this? What should I look up to learn more about why this happens?

<!DOCTYPE html>
<html>
    <head>
        <style>
            .red { color: red; }
            .blue { color: blue; }
        </style>
    </head>
    <body>

        <span class="red">1</span>
        <span class="red">2</span>
        <span class="red">3</span>

        <script>
            var redElements = document.getElementsByClassName("red");
            alert(redElements.length);
            firstRedElement = redElements[0];
            firstRedElement.className = "blue";
            alert(redElements.length);
        </script>
    </body>
</html>
Qaz
  • 1,556
  • 2
  • 20
  • 34
  • 1
    `redElements` is not a _copy_ of `document.getElementsByClassName("red")` - it is the same collection of elements! – James Oct 24 '15 at 17:25
  • 2
    This question has nothing to do with the "duplicates" suggested. Please be more careful! – James Oct 24 '15 at 17:35
  • I agree with the closure. As explained in the other questions, that's because the collection is live. – Oriol Oct 24 '15 at 17:45
  • @Oriol No, it happens because redElements is a reference to the same collection. It doesnt have to be a collection, it could be an object reference, array reference, nothing to do with "live". – James Oct 24 '15 at 17:52
  • @James If you use `document.querySelectorAll(".red")` you also get a reference to the collection. But it isn't live, so it doesn't have this problem. – Oriol Oct 24 '15 at 17:57
  • @Oriol That's nice, but not relevant. Check this question again. – James Oct 24 '15 at 18:00

1 Answers1

0

That's because className function will override the existing class:
Try this:

<script>
        var redElements = document.getElementsByClassName("red");
        alert(redElements.length);
        firstRedElement = redElements[0];
        firstRedElement.className = firstRedElement.className + " blue";
        alert(redElements.length);
    </script>

or you can even try:

firstRedElement.classList.add("blue");
Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28