Explain Codes LogoExplain Codes Logo

How to change CSS property using JavaScript

javascript
javascript-features
css-properties
dom-manipulation
Nikita BarsukovbyNikita Barsukov·Feb 15, 2025
TLDR

Instantly tailor CSS properties of any HTML element with JavaScript using getElementById and adjusting its style:

// David said painting the town red was last season - let's go green! document.getElementById("myElement").style.color = "green";

For compound properties like font-size, use camelCase:

// Making text bigger, because bigger is better-er! document.getElementById("myElement").style.fontSize = "2em";

This live changes of styles serve dynamic interactions.

Get specific: Target your elements

Targeting multiple elements with similar styles is a no-fuss operation with getElementsByClassName:

// Select all the cool kids in the ".myClass" group let elements = document.getElementsByClassName("myClass"); for (let element of elements) { // Give them all lightblue jackets - because why not! element.style.backgroundColor = "lightblue"; }

For the modern code artisan who adores the querySelectorAll and forEach combo, here's how you would loop and style:

// Let's give every .myClass a background to remember! document.querySelectorAll(".myClass").forEach(el => el.style.backgroundColor = "lightblue");

It's raining styles: Change multiple with Object.assign()

Calling Object.assign() is like a fashion overhaul for your element: completely changing its look in a single line of code:

// Like a complete make-over for "myElement"! Object.assign(document.getElementById("myElement").style, { color: "green", fontSize: "20px", border: "1px solid black" });

From Drab to Fab: Toggling class styles

Flipping styles like a fashionista switches outfits - use classList for adding, removing, or toggling a class:

// Get the diva ready for the runway let element = document.getElementById("myElement"); // It's not just a style, it's a statement! element.classList.add("newStyle"); // flip the activeStyle on and off element.classList.toggle("activeStyle");

Hovering around: Styling interactive elements

For hover effects, employ event listeners for an interactive user experience beyond simple :hover:

// Prepare to cast a shadow on "myElement" let element = document.getElementById("myElement"); element.addEventListener('mouseenter', () => { // You're entering the twilight zone! element.style.boxShadow = "0px 0px 15px rgba(0,0,0,0.5)"; }); // The shadow lifts as your mouse departs... element.addEventListener('mouseleave', () => { element.style.boxShadow = "none"; });

One code to suit all: Cross-browser considerations

In a world of diverse browsers, remember to regularily check cross-browser compatibility and use Polyfills for less supported features. Fingers crossed it works on Internet Explorer! 🤞

Clarify Intent: Keep your code legible with comments

Odd behavior? Complex logic? Leave notes - I mean, comments in your JavaScript:

// Everyone loves a golden button... don't they? document.getElementById("myElement").addEventListener("click", function() { this.style.backgroundColor = 'gold'; });

Debugging, or "Why it won't work!"

Is your code pulling a prank on you? Time to console.log() your JavaScript and inspect your browser's developer tools:

// Spilling the secrets - your element's true color revealed! console.log(element.style.color);

Modern syntax: Spread the style!

For whoever loves tidy code, go for this modern, concise spread operator method when merging old and new styles:

// Latest styles now trending on "myElement" let newStyles = { fontSize: '2em', color: 'coral' }; element.style = { ...element.style, ...newStyles };

Simplify and avoid complexity

KISS (Keep It Simple, Stupid!). Start with the least invasive method for the required effect. Some design tweaks are better solved with pure CSS instead of JavaScript.