Category: javascript
dom changing styles and classes
Published on 30 Sep 2026
Explanation
The style property allows JavaScript to modify inline CSS styles directly.
Code:
const box = document.getElementById('box');
box.style.backgroundColor = 'blue';
box.style.padding = '20px';
Explanation
classList.add() adds a CSS class to an element.
Code:
const box = document.getElementById('box');
box.classList.add('active');
Explanation
classList.remove() removes a CSS class from an element.
Code:
box.classList.remove('active');
Explanation
classList.toggle() adds a class if it is absent and removes it if it is present.
Code:
button.addEventListener('click', () => {
box.classList.toggle('dark');
});
Explanation
Using CSS classes is generally cleaner for reusable styling than assigning many inline style properties from JavaScript.
Code:
.highlight {
background: yellow;
font-weight: bold;
}
// JavaScript
box.classList.add('highlight');