0

I cant understand why this does not store a copy of the previous array.

code

console.log(buttons);

var copybtns = [];
for (let i = 0; i < buttons.length; i++) {
copybtns = buttons[i];
    
}

console.log(copybtns);

and I get this in my console enter image description here

My dull html code

<body>
    <div class="container">
        <form action="">
            <select name="changecolor" id="background" onchange="changeToRed(this)">
                <option value="Random">Random</option>
                <option value="Red"">Red</option>
                <option value="Blue">Blue</option>
                <option value="Black">Black</option>
                <option value="Reset">Reset</option>
            </select>
        </form>
        <button>0</button>
        <button class="btn btn-primary">1 </button>
        <button class="btn btn-danger">2</button>
        <button class="btn btn-dark">3</button>
        <button class="btn btn-warning">4</button>
    </div>
</body>

I was watching a tutoprial but wrote the same code but i don't know why its not working

I want a result like this enter image description here

Justin
  • 141
  • 3
  • 12

1 Answers1

1

You can simply use forEach function using querySelectorAll method to store the button in your empty array copybtns

Fiddle Demo: https://jsfiddle.net/efxwbtyu/

//get all buttons
let buttons = document.querySelectorAll('button')

//Original buttons
console.log(buttons)

//store
var copybtns = [];

//foreach
buttons.forEach((data) => copybtns.push(data))

//log the array data
console.log(copybtns);
<button>0</button>
<button class="btn btn-primary">1 </button>
<button class="btn btn-danger">2</button>
<button class="btn btn-dark">3</button>
<button class="btn btn-warning">4</button>
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • but this is the result I get`NodeList [] length: 0 __proto__: NodeList main.js:14 [] length: 0` – Justin Aug 01 '20 at 08:42
  • @Justin It should work fine. Just like it working in my answer above. I am not sure what is this result ? – Always Helping Aug 01 '20 at 09:18
  • @Justin I saw your image above regarding expected results. So you want it like that. I have edited my answer. My `console.log(copybtns)` above in the answer is showing exactly the results you wanted in the picture in your question. Also the js fiddle demo is showing the same results as you wanted in the console. – Always Helping Aug 01 '20 at 09:23
  • Okay I will just make a new project and try again. Thank you so much for the help] – Justin Aug 01 '20 at 14:01