How to add CSS on html using JavaScript?

0 votes
31 views
Ravi Vishwakarma asked 11 days ago in Web Application by Ravi Vishwakarma

How to add CSS on html using JavaScript?

1 Answer

0 votes
Ethan Karla answered 8 days ago by Ethan Karla

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>