In this example, we will see how to add CSS rules to the stylesheet element using JavaScript. First, we will create an HTML document and then add some CSS rules using JavaScript.
Syntax:
let styleText = document.getElementById('GFG').sheet; let st = `.box { width: 100px; height: 100px; }`; styleText.insertRule(st, 0);
Approach: First, we select the stylesheet element using any query selector, and then assign the CSS styles to a variable. After that, use the insertRule() property to add the CSS rules to the stylesheet using JavaScript.
Example 1: In this example, we will add the CSS Rules to the stylesheet of the div element.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > How to add CSS Rules to the Stylesheet using JavaScript? </ title > < style type = "text/css" id = "GFG" > body { text-align: center; } h1 { color: green; } </ style > </ head > < body > < h1 >neveropen</ h1 > < h3 > How to add CSS Rules to the Stylesheet using JavaScript </ h3 > < div class = "box" ></ div > < script > let styleText = document.getElementById('GFG').sheet; let stl = `.box { width: 100px; height: 100px; background-color: green; display: block; margin-left: auto; margin-right: auto; }`; styleText.insertRule(stl, 0); </ script > </ body > </ html > |
Output:
Example 2: In this example, we will add the CSS Rules to the stylesheet of the div element. Here, we will merge all the CSS styles as a string and apply them to the div element.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title > How to add CSS Rules to the Stylesheet using JavaScript? </ title > < style type = "text/css" id = "GFG" > body { text-align: center; } h1 { color: green; } </ style > </ head > < body > < h1 >neveropen</ h1 > < h3 > How to add CSS Rules to the Stylesheet using JavaScript? </ h3 > < div class = "box" ></ div > < script > let styleText = document.getElementById('GFG').sheet let stl = '.box {'; stl += 'width: 100px;'; stl += 'height: 100px;'; stl += 'background-color: green;'; stl += 'display: block;'; stl += 'margin-left: auto;'; stl += 'margin-right: auto;'; stl += 'animation: GFG 5s infinite linear;'; stl += '}'; styleText.insertRule(stl, 0); </ script > </ body > </ html > |
Output: