Skip to content
GitHub

Manipulating Element Styles

Switch to Zen Mode

  • You can directly manipulate an element’s inline styles using the style property (camelCase).
const element = document.getElementById("myElement");
// Set individual style properties (camelCase)
element.style.backgroundColor = 'blue';
element.style.fontSize = '16px';
element.style.marginTop = '10px';
// Get inline style
const bgColor = element.style.backgroundColor;
// Set multiple styles at once
Object.assign(element.style, {
color: 'white',
padding: '10px',
borderRadius: '5px'
});
// Remove a style property
element.style.removeProperty('background-color');
// Set CSS priority
element.style.setProperty('color', 'red', 'important');
javascript

  • Gets the computed styles (including CSS from stylesheets) using window.getComputedStyle(element).
// Get computed style (actual rendered style after CSS is applied)
const computedStyle = window.getComputedStyle(element);
const fontSize = computedStyle.fontSize;
const opacity = computedStyle.getPropertyValue('opacity');
javascript

Classes are a cleaner way to manage styles.

  • Gets or sets the entire class string.
const div = document.getElementById("myDiv");
div.className = "active highlighted";
javascript

The classList provides methods for for manipulating (adding, removing, and toggling) classes:

  • add(...classes): Adds one or more classes.
  • remove(...classes): Removes one or more CSS classes.
  • toggle(class): Toggles a class (adds if absent, removes if present).
  • contains(class): Checks if an element has a specified class.
// Add classes
element.classList.add('new-class', 'another-class');
// Remove classes
element.classList.remove('old-class');
// Toggle a class (add if not present, remove if present)
element.classList.toggle('active');
// Check if an element has a class
const hasClass = element.classList.contains('highlight'); // true or false
// Replace a class
element.classList.replace('old-class', 'new-class');
// Iterate through classes
element.classList.forEach(className => {
console.log(className);
});
javascript

Basic animations can be achieved with DOM manipulation.

  • Schedules a function to run before the next repaint (smooth animations).
function move(element) {
let pos = 0;
function step() {
pos += 1;
element.style.left = pos + "px";
if (pos < 100) requestAnimationFrame(step);
}
requestAnimationFrame(step);
}
move(document.getElementById("box"));
javascript
  • Use classList to trigger CSS transitions.
.box {
transition: all 0.3s;
}
.box.moved {
transform: translateX(100px);
}
css
const box = document.getElementById("box");
box.classList.add("moved");
javascript