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
How to Add CSS Rules to a Stylesheet with JavaScript?
The insertRule() helps us add a rule at a defined position in the stylesheet while deleteRule() deletes a specific style on a web page. The following examples illustrate CSS rules that can be added to a stylesheet using JavaScript.
Insert a Rule
To insert a rule at a defined position, use the insertRule() method. The margin, padding, and box-shadow is also set. First, the custom id is set using the getElementById() −
let newSheet = document.getElementById('custom').sheet
let cs = 'p {';
cs += 'margin: 4%;';
cs += 'padding: 2%;';
cs += 'font-size: 22px;';
cs += 'box-shadow: -10px 4px 0 chartreuse;'
cs += '}';
newSheet.insertRule(cs, 0);
The custom is the id set using the <style> −
<style type="text/css" id="custom">
Example
Let us see the example to insert a rule on a web page −
<!DOCTYPE html>
<html>
<head>
<style type="text/css" id="custom">
body {
background-color: silver;
}
</style>
</head>
<body>
<h1>Custom CSS!</h1>
<p>Woohoo!</p>
<script>
let newSheet = document.getElementById('custom').sheet
let cs = 'p {';
cs += 'margin: 4%;';
cs += 'padding: 2%;';
cs += 'font-size: 22px;';
cs += 'box-shadow: -10px 4px 0 chartreuse;'
cs += '}';
newSheet.insertRule(cs, 0);
</script>
</body>
</html>
Delete a Rule
To delete a rule at a defined position, use the deleteRule() method. First, set the rule using the insertRule() method. The <h2> border is set for the rule −
let mySheet = document.getElementById('demo').sheet
let cs = 'h2 { border: 2px solid green; }'
mySheet.deleteRule(2);
mySheet.insertRule(cs, 0);
The demo is the id set using the <style> −
<style type="text/css" id="demo">
Example
Let us see the example to delete a rule from a web page −
<!DOCTYPE html>
<html>
<head>
<style type="text/css" id="demo">
div {
margin: 3%;
text-align: center;
background-color: powderblue;
}
p {
box-shadow: 0 0 12px rgba(0,0,0,0.6);
}
h2 {
color: red;
}
</style>
</head>
<body>
<div>
<h2>Custom CSS!</h2>
<p>Woohoo!</p>
</div>
<script>
let mySheet = document.getElementById('demo').sheet
let cs = 'h2 { border: 2px solid green; }'
mySheet.deleteRule(2);
mySheet.insertRule(cs, 0);
</script>
</body>
</html>
