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.
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.
Share Improve this question edited Oct 11, 2017 at 7:34 Jay 1,6785 gold badges21 silver badges35 bronze badges asked Oct 11, 2017 at 7:23 Dilakshan SooriyanathanDilakshan Sooriyanathan 1551 gold badge3 silver badges17 bronze badges 1- Possible duplicate of Changing CSS Values with Javascript – Nikola Lukic Commented Oct 11, 2017 at 7:50
4 Answers
Reset to default 3document.querySelector('#h1').style.color = 'your-color';
for multiple css property change use with classname
add .it reduce the code lines in dom
document.querySelector('#h1').classList.add('your-class')
JS:
document.getElementById("elementsId").style.color= "red";
My remendation 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","width: 500px; background-color: yellow;");
$('h1').css('color','#ff5722');
#h1 {
color: 'red';
}
<script src="https://ajax.googleapis./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