1

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';
});
1
  • Maybe using save.classList.style["background-color"] = 'red'; ? Commented May 30, 2017 at 8:40

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.