How to add CSS on html using JavaScript?

Asked 19-Jul-2021
Viewed 392 times

1 Answer


1

In JavaScript, we can add css through style attribute or setAttribute function.

Style Attribute
Syntax

 element.style.style-property=value;
example 

<!DOCTYPE html>
<html>
<body>
<h1>Hello World!</h1>
<button type='button' onclick='myFunction()'>Set background color</button>
<script>
function myFunction() {
  document.body.style.backgroundColor = 'red';
}
</script>
</body>
</html>
setAttribute()
Syntax

 element.setAttribute(attributename, attributevalue);
example

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
  color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<p>Click the button to add a class attribute with the value of 'democlass' to the h1 element.</p>
<button onclick='myFunction()'>Try it</button>
<script>
function myFunction() {
  document.getElementsByTagName('H1')[0].setAttribute('class', 'democlass');
}
</script>
</body>
</html>