Home > OS >  Copy buttons element Array values - Javascript
Copy buttons element Array values - Javascript

Time:05-06

I'm creating a dropdown list that sets and resets colors of buttons nearby. I'm trying to copy an array html button elements into another array. The problem is, When I change the first array of elements(color, wrapping etc..) the copy also gets changed. Here's my code:

    var buttons = document.getElementsByTagName('button');
    var copyallbuttons = [];   
 
     for (let i=0; i<buttons.length; i  )
    {
        let x = buttons[i].style.backgroundColor;
        copyallbuttons[i] = x;
    } 

But when I make changes to buttons, even copyallbuttons gets changed. Please let me know how to copy values of html elements into another array (without reference) so that changing one doesnt affect other. This is basically for the "reset" button on the front end to reload all old styles of the elements.

CodePudding user response:

var buttons = document.getElementsByClassName('changeColour');

for (let i=0; i<buttons.length; i  )
{
    buttons[i].style.backgroundColor ="red";
} 
<button  >Button 1</button>
<button  >Button 2</button>
<button  >Button 3</button>

You can use var buttons = document.getElementsByClassName("example"); and give common class name for buttons which you want to change colour.

CodePudding user response:

function changeColour(colour) {
  var buttons = document.getElementsByClassName('changeColour');

  for (let i=0; i<buttons.length; i  )
  {
      buttons[i].style.backgroundColor = colour;
  } 
}

$(".changeColour").click(function(){
  changeColour("red");
});

$(".resetBtn").click(function(){
  changeColour("black"); //here default colour
});
  • Related