change css file attribute values using JavaScript

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.

Upvotes: 0

Views: 2121

Answers (4)

Munkhdelger Tumenbayar
Munkhdelger Tumenbayar

Reputation: 1874

$('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

Upvotes: 1

Rohit Agrawal
Rohit Agrawal

Reputation: 1521

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

Upvotes: 3

prasanth
prasanth

Reputation: 22490

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

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

Upvotes: 3

sjahan
sjahan

Reputation: 5940

document.querySelector('#h1').style.color = 'your-color';

Upvotes: 3

Related Questions