JavaScript onClick change css

This is probably very simple, I know that you can change the css properties using javascript by doing

document.getElementById('bob').style.background='#000000'; 

But I recently found out that you can do it differently and create a few things, something like this;

 document.getElementById('bob').css='background:#ffffff; color: #000000;'; 

The problem is that I forgot what code is. So what I basically want to achieve is what happens instead of ".css"? Does anyone know the code I need from my head?

+7
source share
4 answers

I think you are looking for the .cssText property from style

 document.getElementById('bob').style.cssText = 'background:#ffffff; color: #000000;'; 

Example: http://jsfiddle.net/Sx5yH/

+19
source

Have a look at this script: http://jsfiddle.net/YSJfz/

 document.getElementById('myDiv').setAttribute('style', 'background: #f00; color: #fff;'); 

All I do is change the style attribute of the element, is that what you wanted to accomplish?

+7
source

I think you are looking to Change the element class with JavaScript . Since you don’t need to hardcode all the style changes in JavaScript itself (which is bad).

So you will have a CSS class like this:

 .myClass { background: #ffffff; color: #000000; } 

And you set this element as follows:

 document.getElementById("MyElement").className += " myClass"; 
+3
source
 document.getElementById('bob').style.cssText = 'background:#ffffff; color: #000000;'; 
+2
source

All Articles