Apply a CSS style with !important declaration using JavaScript
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
|
1 |
document.querySelector('input').className += " inputWidth"; |
CSS
|
1 2 3 |
.inputWidth { width: 200px !important; } |
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.
|
1 |
document.head.innerHTML += '<style> input { width: 200px `!important` } </style>'; |
3. Set value for style attribute
Another approach is to set the CSS style with the !important declaration in the style attribute.
|
1 |
document.querySelector('input').style = 'width: 200px !important'; |
Alternatively, you can use the setProperty() method for setting the value for a CSS property.
|
1 |
document.querySelector('input').style.setProperty('width', '200px', 'important'); |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)