0

What is the proper and fastest way to change CSS values using JavaScript? For example, if I have a style.css file:

#h1 {
 color: 'red';
}

I need to change the color to any other color and update the CSS file.

Jay
  • 1,688
  • 5
  • 20
  • 34
  • Possible duplicate of [Changing CSS Values with Javascript](https://stackoverflow.com/questions/566203/changing-css-values-with-javascript) – Nikola Lukic Oct 11 '17 at 07:50

4 Answers4

3
document.querySelector('#h1').style.color = 'your-color';
sjahan
  • 5,720
  • 3
  • 19
  • 42
3

JS:

document.getElementById("elementsId").style.color= "red";

My recommendation would be not to use Id name like h1 as it may be confusing with the <h1> tag in html. Use more clear variable name like headerId.

for changing multiple css properties use this:

document.getElementById(elementsId).setAttribute("style","wi‌​dth: 500px; background-color: yellow;");
Rohit Agrawal
  • 1,496
  • 9
  • 20
  • 1
    but this will only change the color at that moment. I want to change the css file value also. – Dilakshan Sooriyanathan Oct 11 '17 at 07:32
  • @DilakshanSooriyanathan, you can not update the css file values with javascript however you can change multiple css properties like this `document.getElementById(elementsId).setAttribute("style","width: 500px; background-color: yellow;");` or you can write a class in css in advance and add that class to your element when needed using Js as pointed by prashant – Rohit Agrawal Oct 11 '17 at 07:35
  • You cannot change the css file, CSS is not dynamic. The best you could do is use some kind of preprocessor (Saas/Less), regenerate a CSS file and unload the previous one and load a new one. – sjahan Oct 11 '17 at 07:37
  • Thanks for your instruction. really appreciate that. – Dilakshan Sooriyanathan Oct 11 '17 at 07:38
3

for multiple css property change use with classname add .it reduce the code lines in dom

document.querySelector('#h1').classList.add('your-class')
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

$('h1').css('color','#ff5722');
#h1 {
 color: 'red';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1> this color tho</h1>

Jquery is from javascript so once you learn jquery you will sometimes go back to javascript