Computer >> Computer tutorials >  >> Programming >> Javascript

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 .

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

Example

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

How to Add CSS Rules to a Stylesheet with JavaScript?

Example

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

How to Add CSS Rules to a Stylesheet with JavaScript?