How to Add CSS Rules to a Stylesheet with JavaScript?

CSSJavascriptWeb DevelopmentFront End Technology

The insertRule() helps us add a rule at a defined position in the stylesheet while deleteRule() deletes a specific style .

The following examples illustrate CSS rules that can be added to a stylesheet using JavaScript.

Example

 Live Demo

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

Output

This will produce the following result −

Example

 Live Demo

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

Output

This will produce the following result −

raja
Published on 13-Mar-2021 12:31:18
Advertisements