CSS Getting started with CSS Changing CSS with JavaScript

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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



Got any CSS Question?