JavaScript DOM Styles
Introduction
One of the most powerful features of JavaScript DOM manipulation is the ability to dynamically change the appearance of HTML elements. By modifying CSS properties through JavaScript, you can create interactive web pages that respond to user actions, animate elements, and update the visual presentation of your content without reloading the page.
In this tutorial, we'll explore different ways to manipulate styles using JavaScript's DOM API. You'll learn how to access and modify inline styles, work with CSS classes, and understand when to use each approach.
Accessing and Modifying Element Styles
The style
Property
Every DOM element has a style
property that allows you to directly access and modify inline styles. This property represents the element's style
attribute and provides access to all CSS properties through camelCase notation.
// HTML: <div id="box">Hello World</div>
const box = document.getElementById('box');
// Setting individual style properties
box.style.backgroundColor = 'blue';
box.style.color = 'white';
box.style.padding = '20px';
box.style.borderRadius = '5px';
Notice how CSS properties that contain hyphens are converted to camelCase:
background-color
becomesbackgroundColor
border-radius
becomesborderRadius
font-size
becomesfontSize
Example: Creating a Toggle Button for Dark Mode
Here's a practical example of using the style
property to implement a dark mode toggle:
function toggleDarkMode() {
const body = document.body;
const isDarkMode = body.style.backgroundColor === 'black';
if (isDarkMode) {
// Switch to light mode
body.style.backgroundColor = 'white';
body.style.color = 'black';
} else {
// Switch to dark mode
body.style.backgroundColor = 'black';
body.style.color = 'white';
}
}
// HTML: <button onclick="toggleDarkMode()">Toggle Dark Mode</button>
Getting Computed Styles
The style
property only accesses inline styles defined directly on the element. To get all the applied styles, including those from stylesheets, you need to use getComputedStyle()
:
const element = document.getElementById('myElement');
const styles = window.getComputedStyle(element);
console.log(styles.color); // Returns the computed color
console.log(styles.fontSize); // Returns the computed font size
getComputedStyle()
is read-only; you cannot modify the values returned by it.
Working with CSS Classes
While the style
property is useful for dynamic style changes, it's often better to define styles in CSS and simply apply or remove classes using JavaScript.
Adding and Removing Classes
The classList
API provides methods to manipulate classes:
const element = document.getElementById('myElement');
// Add a class
element.classList.add('highlight');
// Remove a class
element.classList.remove('hidden');
// Toggle a class (add if not present, remove if present)
element.classList.toggle('active');
// Check if an element has a class
if (element.classList.contains('selected')) {
console.log('Element is selected');
}
// Replace one class with another
element.classList.replace('inactive', 'active');
Example: Creating a Tabbed Interface
Here's how you might implement a simple tabbed interface using classes:
function openTab(event, tabName) {
// Hide all tab content
const tabContents = document.getElementsByClassName('tab-content');
for (let i = 0; i < tabContents.length; i++) {
tabContents[i].classList.remove('active');
}
// Remove active class from all tab buttons
const tabButtons = document.getElementsByClassName('tab-button');
for (let i = 0; i < tabButtons.length; i++) {
tabButtons[i].classList.remove('active');
}
// Show the current tab and add active class to the button
document.getElementById(tabName).classList.add('active');
event.currentTarget.classList.add('active');
}
<!-- HTML structure -->
<div class="tab">
<button class="tab-button active" onclick="openTab(event, 'tab1')">Tab 1</button>
<button class="tab-button" onclick="openTab(event, 'tab2')">Tab 2</button>
</div>
<div id="tab1" class="tab-content active">
<p>This is content for Tab 1</p>
</div>
<div id="tab2" class="tab-content">
<p>This is content for Tab 2</p>
</div>
/* CSS */
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.tab-button {
background-color: #f1f1f1;
}
.tab-button.active {
background-color: #ddd;
}
Setting Multiple Styles at Once
Using cssText
If you need to set multiple styles at once, cssText
allows you to define all styles in a single string:
const element = document.getElementById('myElement');
element.style.cssText = 'color: blue; font-size: 16px; padding: 10px; background-color: yellow;';
Be aware that cssText
replaces all inline styles, so any existing inline styles will be lost.
Using Object.assign
You can also use Object.assign
to set multiple styles:
const element = document.getElementById('myElement');
Object.assign(element.style, {
color: 'blue',
fontSize: '16px',
padding: '10px',
backgroundColor: 'yellow'
});
CSS Variables with JavaScript
Modern websites often use CSS variables (custom properties). You can manipulate these with JavaScript as well:
// Set a CSS variable
document.documentElement.style.setProperty('--main-color', '#ff0000');
// Get a CSS variable
const mainColor = getComputedStyle(document.documentElement)
.getPropertyValue('--main-color');
console.log(mainColor); // " #ff0000"
Example: Theme Switcher with CSS Variables
function setTheme(theme) {
const root = document.documentElement;
if (theme === 'dark') {
root.style.setProperty('--bg-color', '#121212');
root.style.setProperty('--text-color', '#ffffff');
root.style.setProperty('--accent-color', '#bb86fc');
} else {
root.style.setProperty('--bg-color', '#ffffff');
root.style.setProperty('--text-color', '#121212');
root.style.setProperty('--accent-color', '#6200ee');
}
}
// HTML:
// <button onclick="setTheme('light')">Light Theme</button>
// <button onclick="setTheme('dark')">Dark Theme</button>
:root {
--bg-color: #ffffff;
--text-color: #121212;
--accent-color: #6200ee;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
button {
background-color: var(--accent-color);
color: white;
}
Animation with JavaScript Styles
You can create animations by changing styles with setTimeout
or setInterval
:
function fadeIn(element) {
let opacity = 0;
element.style.opacity = opacity;
element.style.display = 'block';
const timer = setInterval(() => {
if (opacity >= 1) {
clearInterval(timer);
}
element.style.opacity = opacity;
opacity += 0.1;
}, 50);
}
// Usage
const modal = document.getElementById('myModal');
fadeIn(modal);
Best Practices for DOM Styling
-
Separate concerns: Keep your CSS in stylesheets and use JavaScript to add/remove classes when possible.
-
Batch DOM operations: Minimize direct style manipulations, as they can trigger multiple reflows/repaints.
-
Use CSS transitions: When possible, define transitions in CSS and simply toggle classes with JavaScript.
-
Consider CSS animations: For complex animations, CSS animations are often more performant than JavaScript-based ones.
-
Use CSS variables for themes: They provide a clean way to implement theming across your site.
Real-World Example: Interactive Image Gallery
Let's create a simple image gallery with a magnification effect on hover:
<div class="gallery">
<div class="gallery-item">
<img src="image1.jpg" alt="Image 1">
</div>
<div class="gallery-item">
<img src="image2.jpg" alt="Image 2">
</div>
<div class="gallery-item">
<img src="image3.jpg" alt="Image 3">
</div>
</div>
// Get all gallery items
const galleryItems = document.querySelectorAll('.gallery-item');
// Add event listeners to each item
galleryItems.forEach(item => {
item.addEventListener('mouseover', () => {
// Reset all other items
galleryItems.forEach(otherItem => {
if (otherItem !== item) {
otherItem.style.transform = 'scale(0.9)';
otherItem.style.opacity = '0.7';
}
});
// Enlarge the hovered item
item.style.transform = 'scale(1.1)';
item.style.opacity = '1';
item.style.zIndex = '1';
});
// Reset everything when mouse leaves the gallery
document.querySelector('.gallery').addEventListener('mouseleave', () => {
galleryItems.forEach(item => {
item.style.transform = 'scale(1)';
item.style.opacity = '1';
item.style.zIndex = '0';
});
});
});
.gallery {
display: flex;
gap: 20px;
padding: 20px;
}
.gallery-item {
flex: 1;
transition: all 0.3s ease;
}
.gallery-item img {
width: 100%;
height: auto;
display: block;
}
Summary
JavaScript provides several powerful ways to manipulate CSS styles dynamically:
- The
style
property allows direct manipulation of inline styles getComputedStyle()
lets you access all applied stylesclassList
API provides methods to add, remove, and toggle CSS classes- CSS variables can be modified through JavaScript for theme customization
- Animations can be created by changing styles over time
When deciding how to apply styles with JavaScript, consider:
- Use
classList
for toggling predefined styles - Use direct style manipulation for dynamic values or animations
- Use CSS variables for theme-related properties
By mastering these techniques, you can create dynamic, interactive, and visually appealing web applications that respond to user actions and adapt to different contexts.
Additional Resources
- MDN Web Docs: DOM Style Object
- MDN Web Docs: Element.classList
- CSS-Tricks: A Complete Guide to CSS Custom Properties
Exercises
- Create a button that toggles between light and dark mode using CSS classes.
- Build a simple image carousel that changes the display style of images when navigating.
- Implement a form validation system that changes input styles based on whether the input is valid or invalid.
- Create a responsive navigation menu that changes style based on screen size, using JavaScript to detect window width.
- Design a color picker that updates CSS variables to change the theme of a webpage.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)