Changing CSS with JavaScript

suggest change

Pure JavaScript

It’s possible to add, remove or change CSS property values with JavaScript through an element’s style property.

var el = document.getElementById("element");
el.style.opacity = 0.5;
el.style.fontFamily = 'sans-serif';

Note that style properties are named in lower camel case style. In the example you see that the css property font-family becomes fontFamily in javascript.

As an alternative to working directly on elements, you can create a <style> or <link> element in JavaScript and append it to the <body> or <head> of the HTML document.

jQuery

Modifying CSS properties with jQuery is even simpler.

$('#element').css('margin', '5px');

If you need to change more than one style rule:

$('#element').css({
    margin: "5px",
    padding: "10px",
    color: "black"
});

jQuery includes two ways to change css rules that have hyphens in them (i.e. font-size). You can put them in quotes or camel-case the style rule name.

$('.example-class').css({
    "background-color": "blue",
    fontSize: "10px"
});

See also

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents