Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Add CSS Rules to a Stylesheet with JavaScript?
The insertRule() method helps us add CSS rules to a stylesheet dynamically using JavaScript, while deleteRule() removes existing rules. These methods allow you to modify styles programmatically without editing the original CSS code.
Syntax
// Insert a rule stylesheet.insertRule(rule, index); // Delete a rule stylesheet.deleteRule(index);
Method 1: Insert a CSS Rule
To insert a rule at a defined position, use the insertRule() method. First, get the stylesheet using getElementById() and access its sheet property −
<!DOCTYPE html>
<html>
<head>
<style type="text/css" id="custom">
body {
background-color: lightgray;
}
</style>
</head>
<body>
<h1>Dynamic CSS Rules</h1>
<p>This paragraph will be styled dynamically!</p>
<script>
let newSheet = document.getElementById('custom').sheet;
let cssRule = 'p {';
cssRule += 'margin: 4%;';
cssRule += 'padding: 2%;';
cssRule += 'font-size: 22px;';
cssRule += 'box-shadow: -10px 4px 0 chartreuse;';
cssRule += 'background-color: lightyellow;';
cssRule += '}';
newSheet.insertRule(cssRule, 0);
</script>
</body>
</html>
The paragraph displays with yellow background, chartreuse shadow, larger font size, and increased margin and padding applied through JavaScript.
Method 2: Delete a CSS Rule
To delete a rule at a specific position, use the deleteRule() method. The following example first deletes an existing rule, then inserts a new one −
<!DOCTYPE html>
<html>
<head>
<style type="text/css" id="demo">
div {
margin: 3%;
text-align: center;
background-color: powderblue;
padding: 20px;
}
p {
box-shadow: 0 0 12px rgba(0,0,0,0.6);
padding: 10px;
}
h2 {
color: red;
}
</style>
</head>
<body>
<div>
<h2>Dynamic Rule Replacement</h2>
<p>Watch the h2 style change!</p>
</div>
<script>
let mySheet = document.getElementById('demo').sheet;
let newRule = 'h2 { border: 3px solid green; color: blue; }';
// Delete the existing h2 rule (index 2)
mySheet.deleteRule(2);
// Insert the new rule at the beginning
mySheet.insertRule(newRule, 0);
</script>
</body>
</html>
The h2 heading changes from red text to blue text with a green border, demonstrating the rule deletion and insertion.
Key Points
- Use document.getElementById('id').sheet to access the stylesheet object
- The insertRule() method takes two parameters: the CSS rule string and the index position
- Index 0 inserts the rule at the beginning, making it high priority
- The deleteRule() method removes a rule by its index position
Conclusion
JavaScript's insertRule() and deleteRule() methods provide powerful ways to modify CSS dynamically. These methods are essential for creating interactive web applications that need to change styles based on user actions or conditions.
