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)

Let’s look into the following example to get clear idea on adding new CSS rules while working on JavaScript.

Example

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.

Example

Let’s consider the another example, in which we are adding the CSS rule to the end of the last style sheet.

<!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 theCSS.

Example

In this case, we are running the script to access the div element by using the script mentioned with CSS.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
   <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
   <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</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;
      }`);
   </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.


Advertisements