admin管理员组

文章数量:1402315

My question might sound very silly as i am new to javascript. I have the following piece of Plain JavaScript code. What i am trying to achieve is to change background-color of the button when its clicked. I am trying to implement this using plain javascript. No jquery or any other framework.

JS

var save = document.querySelector('.wrapper .content button');
save.addEventListener('click', function () {    
    save.classList.style.background-color = 'red';
});

My question might sound very silly as i am new to javascript. I have the following piece of Plain JavaScript code. What i am trying to achieve is to change background-color of the button when its clicked. I am trying to implement this using plain javascript. No jquery or any other framework.

JS

var save = document.querySelector('.wrapper .content button');
save.addEventListener('click', function () {    
    save.classList.style.background-color = 'red';
});
Share Improve this question asked May 30, 2017 at 8:39 ShaSha 1,9946 gold badges35 silver badges60 bronze badges 1
  • Maybe using save.classList.style["background-color"] = 'red'; ? – Ioan Commented May 30, 2017 at 8:40
Add a ment  | 

3 Answers 3

Reset to default 6

You have to do this

var save = document.querySelector('.wrapper .content button');
save.addEventListener('click', function () {    
    save.style['background-color'] = 'red';
});

You can also access the background-color property of style this way

save.style.backgroundColor = 'red';

CSS properties with a - like (background-color) are represented in camelCase in Javascript (backgroundColor) objects.

SNIPPET

var save = document.querySelector('.con');
save.addEventListener('click', function () {    
    save.style['background-color'] = 'yellow';
    //or  save.style.backgroundColor = 'yellow';
});
.con{
  width:100px;
  height:100px;
  background-color:red;
}
<div class="con"></div>

It's element.style.backgroundColor and not element.classList.style.background-color

var save = document.querySelector('.demo');
save.addEventListener('click', function() {
  this.style.backgroundColor = 'red';
});
<div class='demo'> Click me </div>


Detail

When you write save.classList.style.background-color Javascript read a subtraction like save.classList.style.background - color.

var save = document.querySelector('button');
save.addEventListener('click', function () {    
    save.style.backgroundColor = 'red';
});

本文标签: Adding style to a div through JavaScript classListStack Overflow