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.
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: