skip to Main Content

I want to store all the existing button names into an array(copyAllButtons) by using the push function.
However, after the for-loop, there is still nothing inside copyAllButtons.

I am trying to make a reset function that required the array(copyAllButtons) to restore all the button names saved.

Can anyone help me? Thank you.

var all_buttons = document.getElementsByTagName('button'); //all button names are saved 

var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
  copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####

This is my file:
https://drive.google.com/file/d/1qbAAHClxJhNQUFyvrSklbGwX9tbsEsL8/view?usp=sharing

message of console.log(copyAllButtons)
message of console.log(copyAllButtons)

element inside all_buttons
element inside all_buttons

code related:JS

//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved 

var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
  copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####

function buttonColorChange(buttonThingy) {
  if (buttonThingy.value === 'red') {
    buttonsRed();
  } else if (buttonThingy.value === 'green') {
    buttonsGreen();
  } else if (buttonThingy.value === 'reset') {
    buttonsColorReset();
  } else if (buttonThingy.value === 'random') {
    randomColors();
  }
}

function buttonsRed() {
  for (let i = 0; i < all_buttons.length; i++) {
    all_buttons[i].className = 'btn btn-danger';
  }
}

function buttonsGreen() {
  for (let i = 0; i < all_buttons.length; i++) {
    all_buttons[i].className = 'btn btn-success';
  }
}

    function buttonsColorReset() {    //##function that i am working on##
  for (let i = 0; i < all_buttons.length; i++) {
    all_buttons[i].classList.remove(all_buttons[i].classList[1]);
    all_buttons[i].classList.add(copyAllButtons[i]);
  }
}

function randomColors() {
  for (let i = 0; i < all_buttons.length; i++) {
    var x = Math.floor(Math.random() * 4);
    var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
    all_buttons[i].className = 'btn ' + y[x];
  }
}

HTML

<div class="container-4">
    <h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
    <div class="flex-box-pick-color">
      <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>

CSS:

.container-1, .container-2 , .container-3 ,.container-4{
  border: 1px solid blue;
  width:75%;
  margin: 0 auto;
  text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
  display:flex;
  border:1px solid purple;
  padding: 10px;
  flex-wrap:wrap;
  flex-direction: row;
  justify-content: space-around;
  
}

All my code for reference:
javascript:

function ageInDays() {


  var birthYear = prompt("What year were you born?")
  var days = (2021 - birthYear) * 365

  var h1 = document.createElement('h1')
  var textAnswer = document.createTextNode('You are ' + days + ' days old')

  h1.setAttribute('id', 'days');
  h1.appendChild(textAnswer)
  document.getElementById('flex-box-result').appendChild(h1)
}


function reset() {
  document.getElementById('days').remove()
}

function generateCat() {
  var image = document.createElement('img');
  var div = document.getElementById('flex-cat-gen');
  image.src = "https://thecatapi.com/api/images/get?format=src&type=gif&size=small";
  div.appendChild(image);
}

//challenge3 rock paper scissors
function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

function randToRpsInt() {
  return Math.floor(Math.random() * 3);
}

function numberToChoice(number) {
  return ['rock', 'paper', 'scissors'][number]
}
function rpsGame(yourChoice) {
  var result;
  console.log(yourChoice.id);
  var humanChoice, botChoice;
  var message
  humanChoice = yourChoice.id;
  botChoice = numberToChoice(randToRpsInt());



  console.log(botChoice);
  if (humanChoice === 'rock') {
    if (botChoice === 'rock') {
      result = "tie"
      console.log("tie");
    }
    else if (botChoice === 'paper') {
      result = "lost"
      console.log("You Lost>_<");
    }
    else {
      result = "win"
      console.log("You Win OAO");
    }
  }

  else if (humanChoice === 'paper') {
    if (botChoice === 'rock') {
      result = "win";
      console.log("You Win OAO");
    }
    else if (botChoice === 'scissors') {
      result = "lost";
      console.log("You Lost>_<");
    }
    else {
      result = "tie";
      console.log("tie");
    }
  }
  //scissors
  else {
    if (botChoice === 'paper') {
      result = "win";
      console.log("You Win OAO");
    }
    else if (botChoice === 'rock') {
      result = "lost";
      console.log("You Lost>_<");
    }
    else {
      result = "tie";
      console.log("tie");
    }
  }
  message = finalMessage(result);
  rpsFrontEnd(humanChoice, botChoice, message);





}
function finalMessage(result) {
  if (result === "lost")
    return { 'message': 'You lost!', 'color': 'red' };
  else if (result === "win")
    return { 'message': 'You won!', 'color': 'green' };

  else
    return { 'message': 'You tied!', 'color': 'yellow' };
}


function rpsFrontEnd(humanImageChoice, botImageChoice, finalMessage) {
  var imagesDatabase = {
    'rock': document.getElementById('rock').src,
    'paper': document.getElementById('paper').src,
    'scissors': document.getElementById('scissors').src
  }
  document.getElementById('rock').remove();
  document.getElementById('paper').remove();
  document.getElementById('scissors').remove();

  var humanDiv = document.createElement('div');
  var botDiv = document.createElement('div');
  var messageDiv = document.createElement('div');

  humanDiv.innerHTML = "<img src='" + imagesDatabase[humanImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(37,50,233,1);'>"
  botDiv.innerHTML = "<img src='" + imagesDatabase[botImageChoice] + "' height=150 width=150 style='box-shadow: 0px 10px 50px rgba(3243,38,24,1);'>"
  messageDiv.innerHTML = "<h1 style='color: " + finalMessage['color'] + "; font-size: 60px;padding:30px; '>" + finalMessage['message'] + "</h1>"
  document.getElementById('flex-box-rps-div').appendChild(humanDiv);
  document.getElementById('flex-box-rps-div').appendChild(messageDiv);
  document.getElementById('flex-box-rps-div').appendChild(botDiv);


}



//challenge4
var all_buttons = document.getElementsByTagName('button'); //all button names are saved 

var copyAllButtons = [];
console.log(all_buttons);
for (let i = 0; i < all_buttons.length; i++) {
  copyAllButtons.push(all_buttons[i].classList[1]);
}
console.log(copyAllButtons); //####Button array is empty####

function buttonColorChange(buttonThingy) {
  if (buttonThingy.value === 'red') {
    buttonsRed();
  } else if (buttonThingy.value === 'green') {
    buttonsGreen();
  } else if (buttonThingy.value === 'reset') {
    buttonsColorReset();
  } else if (buttonThingy.value === 'random') {
    randomColors();
  }
}

function buttonsRed() {
  for (let i = 0; i < all_buttons.length; i++) {
    all_buttons[i].className = 'btn btn-danger';
  }
}

function buttonsGreen() {
  for (let i = 0; i < all_buttons.length; i++) {
    all_buttons[i].className = 'btn btn-success';
  }
}



 function buttonsColorReset() {    //##function that i am working on##
      for (let i = 0; i < all_buttons.length; i++) {
        all_buttons[i].classList.remove(all_buttons[i].classList[1]);
        all_buttons[i].classList.add(copyAllButtons[i]);
      }
    }

function randomColors() {
  for (let i = 0; i < all_buttons.length; i++) {
    var x = Math.floor(Math.random() * 4);
    var y = ['btn-primary', 'btn-danger', 'btn-warning', 'btn-success'];
    all_buttons[i].className = 'btn ' + y[x];
  }
}

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
  <title>challenge game</title>
</head>

<body>
  <script src="home.js"></script>

  <div class="container-1">
    <h2>Challenge 1: Your Age in Days</h2>
    <div class="flex-box-container-1">
      <div> <button class="btn btn-primary" onclick="ageInDays()">Click Me</button></div>
      <div> <button class="btn btn-danger" onclick="reset()">Reset</button></div>
    </div>
  </div>

  <div class="flex-box-container-1">
    <div id="flex-box-result">


    </div>
  </div>

  <div class="container-2">
    <h2>Challenge 2: Cat Generator</h2>
    <button class="btn btn-success" id="cat-generator" onClick="generateCat()">Generate Cat</button>
    <div class="flex-box-container-2" id="flex-cat-gen">

    </div>
  </div>

  <div class="container-3">
    <h2>Challenge 3:Rock,Paper,Scissors</h2>
    <div class="flex-box-rps" id="flex-box-rps-div">
      <img id="rock" src="https://cdn.drawception.com/images/panels/2017/2-4/wqmCPbxybn-4.png" alt=""
        onClick="rpsGame(this)" width="250" height="250">
      <img id="paper" src="https://sc04.alicdn.com/kf/UTB8apntp0nJXKJkSaiyq6AhwXXaR.jpg" alt="" onClick="rpsGame(this)"
        width="250" height="250">
      <img id="scissors" src="https://www.collinsdictionary.com/images/full/scissors_100136453.jpg" alt=""
        onClick="rpsGame(this)" width="250" height="250">
    </div>
  </div>

  <div class="container-4">
    <h2 id="change-my-color">Challenge 4:Change the color of all buttons</h2>
    <div class="flex-box-pick-color">
      <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>

CSS:

.container-1, .container-2 , .container-3 ,.container-4{
  border: 1px solid blue;
  width:75%;
  margin: 0 auto;
  text-align: center;
}
.flex-box-container-1, .flex-box-container-2,.flex-box-rps,.flex-box-pick-color{
  display:flex;
  border:1px solid purple;
  padding: 10px;
  flex-wrap:wrap;
  flex-direction: row;
  justify-content: space-around;
  
}

.flex-box-container-1 div{
  display:flex;
  padding: 10px;
  border: 1 px solid black;
  align-items: center;
}



.flex-box-container-2 img{
  
margin:10px;
  box-shadow: 0px 10px 50px rgba(0,0,0,0.7);
 
}

.flex-box-rps img:hover{
  box-shadow: 0px 10px 50px rgba(37,50,233,1);
}

2

Answers


  1. Chosen as BEST ANSWER

    After searching for a long time, I found that I made a mistake in index.html, script tag should be put at the end of the body.


  2. Map button properties to a new array for later use, a minimal reproducable example.

    // map button.btn properties to strings with id and class list
    const all_buttons = [...document.querySelectorAll('button.btn')]
      .map(b => `button#${b.id}, class: ${[...b.classList].join(', ')}`);
    console.log(all_buttons);
    
    // so ...
    
    // save original classNames
    const initialButtonClasses = [...document.querySelectorAll('button')]
      .map(bttn => [...bttn.classList]);
    // replacement classes
    const green = [`btn`, `green`];
    
    document.addEventListener(`click`, handle);
    
    function handle(evt) {
      if (evt.target.dataset.reset) {
        return document.querySelectorAll('button.btn')
          .forEach((btn, i) => {
            btn.classList.remove(...btn.classList);
            btn.classList.add(...initialButtonClasses[i]);
          });
      }
      if (evt.target.dataset.green) {
        return document.querySelectorAll('button.btn')
          .forEach((btn, i) => {
            btn.classList.remove(...btn.classList);
            btn.classList.add(...green);
          });
      }
    }
    .green {
      color: green;
    }
    <button id="a" class="btn z">bttnA</button>
    <button id="b" class="btn y">bttnB</button>
    <button id="c" class="btn x">bttnC</button>
    
    <button data-green="1">all green</button>
    <button data-reset="1">reset</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search