JavaScript style property is used to add, get and change css in javascript. style is property of HTMLElement in DOM. This can change css on events like, click, mouseover, mouseout etc.

Style property can also change theme on click of button or any other event. Like user can choose different color theme as per his preference.

JavaScript Style property/method


JavaScript Style

Javascript style property is used to set css to html elements. This is applicable to DOM Elements only. After document element, style property is used. All the css properties are used in camel case, for exp fontSize. See example


document.body.style.color="red";                
document.body.style.fontSize="14px";                
            

After running this code in Javascript, JS will replace current stylesheet with new properties in DOM. We can check new properties in Browser's Inspect.


Change font color on click

In the next example, we will change font color on mouse click. See example below

This is dummy text


<button class="green">Green</button> 
<button class="yellow">Yellow</button> 
<button class="red">Red</button> 
<span class="exp">This is dummy text</span> 
           

<script>            
document.querySelector(".green").onclick=function(){
    document.querySelector(".exp").style.color="green";
};

document.querySelector(".yellow").onclick=function(){
    document.querySelector(".exp").style.color="yellow";  
};
                        
document.querySelector(".red").onclick=function(){
    document.querySelector(".exp").style.color="red";
});
</script>
                          
            

If !important is used in CSS code, than style property cannot overwrite current css.


JavaScript getComputedStyle

JavaScript getComputedStyle method is used to get style of html elements in JavaScript String. getComputedStyle is a window method with parameter HTMLElement. See how to get css in javascript.


    getComputedStyle(document.body).fontSize;    // return "14px"
    getComputedStyle(document.body).display;    // return "block"
    
    getComputedStyle(document.head).display;    // return "none"

If an HTML Element is having both class and id, and both class and id are used in css code, getComputedStyle will return value of id as id is more specific than class.
See CSS Selectors Specificity for the reason.

Show and hide text on button click

This is example text


<button class="toggle">Hide Text</button> 
<span class="exp">This is example text</span> 

<script>            
document.querySelector(".toggle").onclick=function(){
    var x=document.querySelector(".exp");
    var y=getComputedStyle(x).display;
    
    if(y=="none"){
        x.style.display="inline";
    }
    else{
        x.style.display="none";
    }   
};
</script>