Manipulate CSS with JavaScript or jQuery.
Why change CSS styles with JavaScript or jQuery?
It is often necessary to change the formatting of an HTML page after it has loaded, which requires modifying the page's CSS styles using a language that can be executed on the user's computer (client-side).
- Displaying or hiding certain input fields based on previous entries made by the user. Example: hiding the "Maiden Name" input field when an initial entry indicates that the person is male.
- Application of CSS properties whose values are calculated, which helps to compensate for CSS's weakness in terms of calculations.
On the other hand, JavaScript is now useless for:
- Considering the device capabilities: refer to the
@mediadirective, which allows you to manage the terminal's specifics using pure CSS. - Similarly, reactions to user actions, such as moving the mouse pointer, can be easily defined with pseudo-classes, the most commonly used being
:hover. - The animations are fully supported by CSS (see the
@keyframesdirective) and do not require any additional code. However, we present some JavaScript later to configure or define an animation.
Elements of syntax.
Values, even if they are numbers, are always considered as text by JavaScript. First, because it is often necessary to specify the unit.
But even if the unit does not need to be specified (value 0 or a unitless value), it is recommended to enclose the value in single or double
quotes in the JavaScript code.

el.style.margin='0';
In a few rare cases, the CSS value must be enclosed in quotation marks or apostrophes, for example, the name of a font containing spaces. Care must be taken not to create confusion between the JavaScript delimiter and the CSS delimiter. But, since both languages accept apostrophes or quotation marks equally, the solution is simple:

el.style.fontFamily='"Times New Roman", serif';
JavaScript and jQuery accept property names written in kebab-case as well as in camel-case.
This only makes a difference for property names composed of multiple words, which is still quite common:
font-family, border-top-right-radius, etc.
JavaScript code examples.
Change the value of a property for ONE element.
The result will be equivalent to adding a style attribute to the element identified by its id.

div id="id" style="font-size:12px".../div

const el = document.getElementById('id');
el.style['font-size']='12px';
A second syntax is possible, by considering style not as an array, but as an object.

const el = document.getElementById('id');
el.style.fontSize='12px';
When multiple property values need to be changed, it will be simpler to use the following syntax. As it is written, the code clears all previously defined
styles on the element; to keep them, simply replace the = sign with the += operator.

const el = document.getElementById('id');
el.style.cssText='font-size:12px; font-weight:bold; color:red;';
Read the value of a property for ONE element.
The code below retrieves the value of a property assigned to an element via its style attribute. It is thus the counterpart to the previous code,
which assigned a value to a property via an element's style attribute. Property values set via a CSS selector are not retrieved by this code.
For that, refer to the example on computed values.

const el = document.getElementById('id');
alert(el.style['font-size']);
Read the computed value of a property for ONE element.
The computed value of a property can have several origins:
- A value assigned via the
styleattribute of an element. - A value assigned via a CSS selector, after resolving conflicts according to CSS Priorities.
- An inherited value.
- Failing that, the computed value will be the property's initial value.
For each property, the computed value is always expressed in the same form, even if there are multiple syntaxes for defining it. For example, relative units
are generally converted into absolute units after a calculation that takes the context into account; dimension units are converted into pixels, even if they
were defined in another unit; there are many syntaxes for defining a color (hexadecimal code, color name, hsl() function, etc.), but the computed
value is always expressed with the rgb() function or rgba() if a transparency percentage needs to be specified.
The computed value cannot be set directly since it results from a calculation involving the cascade of inheritance and priority rules, but it is always
possible to read this computed value. The code example below displays the computed value of the font-size property for an element identified
by its id:

const el = document.getElementById('id');
alert(window.getComputedStyle(el).getPropertyValue('font-size'));
Add a class to an element.
If styles are already associated with the added class, they will take effect immediately. This solution has at least two advantages:
- Apply a whole series of CSS rules to an element in a single statement.
- Keep all CSS codes grouped in the stylesheet.

const el = document.getElementById('id');
el.classList.add("nom-classe");
Remove a class from an element.
This is the symmetrical code of the previous one. The styles associated with the class being removed are immediately disabled for this element.

const el = document.getElementById('id');
el.classList.remove("nom-classe");
Set new valid CSS rules for the page.
This syntax allows you to define styles that can be applied to multiple elements on the page using CSS selectors. Compared to the previous code, this solution is certainly a bit more complex, but it offers many advantages:
- It is possible to define styles for pseudo-classes or pseudo-elements. In our example,
:hover. - Ability to define animations with the
@keyframesdirective. This is not about having the animation performed by JavaScript, but about defining or configuring it.
- Ability to download fonts using the
@font-facedirective.
- More generally, possibility to use any of the CSS at-rules.
Be careful with the syntax subtleties in JavaScript: since CSS code is generally written on multiple lines, you need to use the backtick delimiter `
(accessible on Windows with the keys ALTGR 7).

const style = document.createElement('style');
style.innerHTML = `
.classe {color:red; font-size:12px;}
#id {color:green; font-weight:bold;}
a:hover {background-color:yellow;}
`;
document.head.appendChild(style);
The style variable can be retained (declared globally). It may be useful if, later on, the styles need to be removed.

document.head.removeChild(style);
Add a stylesheet to the page.
This code example links a new stylesheet to the page. The formatting of the page is immediately redefined according to the new styles.

const link = document.createElement('link');
link.href = '.../fichier.css';
link.type = 'text/css';
link.rel = 'stylesheet';
document.head.appendChild(link);
jQuery code examples.
JQuery code is generally shorter than JavaScript code, but of course the JQuery library must be referenced in the head section of the page
(v.v.v corresponds to the version of JQuery to use):

script src=".../jquery-v.v.v.min.js"/script
Note: jQuery, just like JavaScript, accepts property names written in kebab-case or camel-case.
Change the value of a property for ONE element.

$('#id').css('font-size','12pt');
// ou $('#id').css('fontSize','12pt');
Read the computed value of a property.

alert($('#id').css('font-size'));
Add CSS rules to a page.
This syntax is the one that offers the most possibilities: applying CSS rules to pseudo-elements or pseudo-classes, defining directives,
configuring an animation with @keyframes , etc.

To make the syntax more readable, the CSS rules have been written on multiple lines. The syntax allows this as long as the delimiter `
(backtick) is used.

$('head').append(`
style
#id {color:red;}
a:hover {background:red;}
/style
`);
Add a stylesheet to the page.
This code example works on the same principle as the previous one, but instead of adding a style tag, we add a link tag to the head section of the page.

$('head').append('link href=".../fichier.css" rel="stylesheet" /');