---
title: "How to add CSS on html using JavaScript?"  
description: "How to add CSS on html using JavaScript?"  
author: "Ravi Vishwakarma"  
published: 2021-07-19  
canonical: https://answers.mindstick.com/qa/93764/how-to-add-css-on-html-using-javascript  
category: "web application"  
tags: ["javascript", "html5", "css cascading style sheets"]  
reading_time: 1 minute  

---

# How to add CSS on html using JavaScript?

How to [add](https://yourviews.mindstick.com/story/4883/5-signs-you-need-to-add-more-protein-to-your-diet) [CSS](https://www.mindstick.com/forum/514/background-gradient-ie7-css-problem) on [html](https://www.mindstick.com/articles/12368/why-are-html-themes-the-first-selection-of-designers) using [JavaScript](https://www.mindstick.com/articles/1530/design-a-simple-stylish-calculator-using-html-css-and-javascript)?

## Answers

### Answer 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>
```

\


---

Original Source: https://answers.mindstick.com/qa/93764/how-to-add-css-on-html-using-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
