Manipulating Element Styles
- You can directly manipulate an element’s inline styles using the
styleproperty (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 styleconst bgColor = element.style.backgroundColor;
// Set multiple styles at onceObject.assign(element.style, { color: 'white', padding: '10px', borderRadius: '5px'});
// Remove a style propertyelement.style.removeProperty('background-color');
// Set CSS priorityelement.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 classeselement.classList.add('new-class', 'another-class');// Remove classeselement.classList.remove('old-class');// Toggle a class (add if not present, remove if present)element.classList.toggle('active');// Check if an element has a classconst hasClass = element.classList.contains('highlight'); // true or false// Replace a classelement.classList.replace('old-class', 'new-class');// Iterate through classeselement.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
classListto trigger CSS transitions.
.box { transition: all 0.3s;}.box.moved { transform: translateX(100px);}css
const box = document.getElementById("box");box.classList.add("moved");javascript