How to add a CSS class to an HTML element using JavaScript?
Hello everyone! I just started learning JavaScript and came across this task: I need to dynamically change the style of an element on the page when a button is clicked. I know this can be done by adding a CSS class, but I can't figure out how to implement it correctly.
I have a simple HTML markup:
```html
This block should change color
```
And a CSS class I want to add:
```css
.highlight {
background-color: yellow;
font-weight: bold;
}
```
I tried writing this code, but it doesn't work:
```javascript
let div = document.getElementById('myDiv');
div.class = 'highlight'; // Doesn't work
```
Then I found something about `className` online, tried this:
```javascript
div.className
``` No answers yet.
Log in to leave an answer