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
3 Answers
Reset to default 6You 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
版权声明:本文标题:Adding style to a div through JavaScript classList - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744337285a2601266.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论