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.

1

4 Answers 4

3
document.querySelector('#h1').style.color = 'your-color';
Sign up to request clarification or add additional context in comments.

Comments

3

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

document.querySelector('#h1').classList.add('your-class')

Comments

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;");

4 Comments

but this will only change the color at that moment. I want to change the css file value also.
@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
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.
Thanks for your instruction. really appreciate that.
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

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.