0

can you tell me why copy.AllButtons.push doesn't work? Google Chrome console:

HTMLCollection []
    0: button.btn.btn-primary
    1: button.btn.btn-danger
    2: button.btn.btn-warning
    3: button.btn.btn-success
    length: 4
    __proto__: HTMLCollection
script.js:9 

[]
length: 0
__proto__: Array(0) <-Why this array is empty?

let all_buttons = document.getElementsByTagName('button');
console.log(all_buttons);
const copyAllButtons = [];
for (let i=0; i < all_buttons.length; i++){
    copyAllButtons.push(all_buttons[i]);
}
console.log(copyAllButtons);
#main_container{
    width: 75%;
    margin: 0 auto;
    text-align: center;
}
.flex-box-pick-color{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Challenge 4</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src='script.js'></script>
</head>
<body>
    <div id='main_container'>
        <div class = 'container-2'>
            <h2 id='changeMyColor'>Challenge 4: Change the color of all buttons!</h2>            
        </div>
        <div class = 'flex-box-pick-color' id='game'>
            <form action=''>
                <select name='backdrop' id='background' onchange="buttonColorChange(this)">
                    <option value="random">Random</option>
                    <option value="Red">Red</option>
                    <option value="green">Green</option>
                    <option value="reset">Reset</option>
                </select>
            </form>
            <button class='btn btn-primary'>Wee!</button>
            <button class='btn btn-danger'>Yahoo</button>
            <button class='btn btn-warning'>Google!</button>
            <button class='btn btn-success'>Facebook!</button>
            
        </div>
        
    </div>
</body>
</html>
Barmar
  • 596,455
  • 48
  • 393
  • 495
Mikołaj K
  • 25
  • 4
  • You can try to wait for `DOMContentLoaded` event before trying to query the DOM elements. `document.addEventListener("DOMContentLoaded", function(event) { ... });` – Harun Yilmaz Jul 22 '20 at 17:42

1 Answers1

2

Since your script is in the head, all_buttons will be an empty collection at the time it runs - therefore none of the code in the loop actually executes.

Your console.log(all_buttons) is non-empty because the getElementsByTagName method returns a "live" collection, and due to the way browser consoles log objects "lazily", you're seeing the later value, not the one it had at the time you logged it.

Among several possible fixes, the easiest and best practice is just to move your script to the end of the body.

Robin Zigmond
  • 14,041
  • 2
  • 16
  • 29