Change CSS Style of Elements with JavaScript and JQuery

Learn how to change CSS styles of HTML elements using plain JavaScript or JQuery in this short tutorial.

1789 views

Edited: 2019-09-11 16:31

Changing the CSS styles of an HTML element can be easily done using JQuery, in which case you will be using the CSS method to add- and remove individual properties.

$("#unique_element_id").css("display", "block");

You can also select by element or class name, just as you would when writing your CSS directly.

You can also set multiple properties at the same time. To do this, simply separate each property with a comma:

$("p").css({"background": "rgb(250,0,0)", "font-size": "2em"});

Using plain JavaScript

If you prefer to use plain JavaScript, you can either control the styling by changing the style attribute of the element, or by using the style object. The first one might be easier for people who have not memorized the properties for changing the different CSS.

var element = document.getElementById("unique_element_id");
element.style.property = "background: #fff;font-size:2em;";

The style object has its own properties to change the CSS of an element. The names are easy to guess, as they are basically the same as the CSS properties without spaces. (I.e: marginTop, marginRight, margin, background, backgroundColor, border, borderTop. Etc.)

document.getElementById("unique_element_id").style.background = "#fff";

Tell us what you think:

  1. You can either use a pure JavaScript solution, or you can choose to go with a library such as JQuery. Either way, this short tutorial show how it is done. Enjoy!
  2. How to show and hide elements using the jquery sliding effects.
  3. In this tutorial you may learn how to create a fade effect using Jquery. With basic JavaScript it can be quite tough, and this is where Jquery may alleviate some of the coding burden.

More in: Jquery Tutorials