This post will discuss how to apply a CSS style with !important declaration to an element using pure JavaScript.

There are several alternatives in plain JavaScript to apply a CSS style with !important declaration to an HTML element.

1. Create a CSS style in a stylesheet

Here, the idea is to create a CSS style with !important declaration inside a class and apply that class to the element. In plain JavaScript, the className attribute can be used to get and set the value of the class attribute of the specified element. So, we can use this as:

JS


CSS



Edit in JSFiddle

2. Create a CSS style in a <style> element

Here, the idea is to create a CSS style with !important declaration in a <style> element and append it to the document head. In plain JavaScript, you can use the innerHTML property of Document.head to append the <style> element to end of the <head> element.

Edit in JSFiddle

3. Set value for style attribute

Another approach is to set the CSS style with the !important declaration in the style attribute.

Edit in JSFiddle

 
Alternatively, you can use the setProperty() method for setting the value for a CSS property.

Edit in JSFiddle

 
Be careful with this approach, as this would replace any style modification you may have performed earlier in the HTML style attribute or through direct DOM manipulation of the style property.

That’s all about applying a CSS style with !important declaration using JavaScript.