Insert a new CSS rule while working on JavaScript?

Adding a new CSS rule can help to create the desired look and feel for your web page or application. This article will explain how to insert a new CSS rule while working on JavaScript.

It will provide step-by-step instructions on how to write and apply the necessary code in order to achieve the desired result. Additionally, we will also discuss some of the potential problems that may arise when inserting a new CSS rule into an existing project.

The style sheet language known as CSS (cascading style sheets), is used to shape the HTML elements that will be displayed as a web page in browsers. The website that was built using HTML will look unappealing without CSS.

insertRule() in JavaScript

A new CSS rule is added to the current style sheet using the insertRule() method. Despite the fact that insertRule() is only a CSSStyleSheet method, it actually inserts the rule into the CSSStyleSheet. Its internal CSSRuleList is called cssRules.

Syntax

Following is the syntax for insertRule()

insertRule(rule)
insertRule(rule, index)

Parameters

  • rule - A string representing the CSS rule to be inserted
  • index (optional) - Position where the rule should be inserted. Defaults to the end of the stylesheet

Method 1: Creating and Inserting CSS Dynamically

In the following example we are running a script which helps in inserting both HTML and CSS together using JavaScript.

<!DOCTYPE html>
<html>
<body>
   <script>
      document.querySelector('body').innerHTML += '<div id="tutorial">Welcome</div>';
      function insert( code ) {
         var style = document.createElement('style');
         if (style.styleSheet) {
            style.styleSheet.cssText = code;
         } else {
            style.innerHTML = code;
         }
         document.getElementsByTagName("head")[0].appendChild( style );
      }
      insert(
         "#tutorial {color: #1C2833; font-size: 35px;}" + "body {background-color: #CCCCFF;}"
      )
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of text along with applied CSS for both text and background. This is caused by the event that is triggered, when the user executes the script.

Method 2: Using insertRule() Method

Let's consider another example, in which we are adding the CSS rule to the end of the last style sheet using the modern insertRule() approach.

<!DOCTYPE html>
<html>
<body>
   <script>
      var css = new function() {
         function addStyle() {
            let head = document.head;
            let style = document.createElement("style");
            head.appendChild(style);
         }
         this.insert = function(rule) {
            if(document.styleSheets.length == 0) { addStyle(); }
            let sheet = document.styleSheets[document.styleSheets.length - 1];
            let rules = sheet.rules;
            sheet.insertRule(rule, rules.length);
         }
      }
      css.insert("body { background-color: #DFFF00}");
   </script>
</body>
</html>

On running the above script, web-browser displays the change in color result, making the event trigger, which helps in applying the CSS.

Method 3: Direct insertRule() Usage

In this case, we are running the script to access the div element by using the script mentioned with CSS and applying styles directly using insertRule().

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>CSS Rule Insertion</title>
</head>
<body>
   <div id="demo">
      This is a JavaScript program
   </div>
   <script>
      var creatingStyle = document.createElement("style");
      document.head.appendChild(creatingStyle);
      creatingStyle.sheet.insertRule(`#demo{
         background-color: red;
         padding: 20px;
         border-radius: 5px;
      }`);
   </script>
</body>
</html>

When the script gets executed, it will generate an output consisting of text applied with CSS on the webpage as a result of the event that was triggered, when the user executed the script.

Comparison of Methods

Method Pros Cons Best Use Case
innerHTML/cssText Simple, widely supported Overwrites existing styles Setting multiple rules at once
insertRule() Precise control, doesn't overwrite More complex syntax Adding single rules dynamically
Direct sheet access Modern, efficient Requires stylesheet existence Professional applications

Key Points

  • Always check if stylesheets exist before using insertRule()
  • The insertRule() method is more efficient than replacing entire stylesheets
  • Use proper CSS syntax in rule strings to avoid errors
  • Consider browser compatibility when choosing methods

Conclusion

JavaScript provides multiple ways to insert CSS rules dynamically. Use insertRule() for precise control and better performance, while innerHTML works well for simple scenarios. Choose the method based on your specific requirements and browser support needs.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements