Explain Codes LogoExplain Codes Logo

Changing CSS Values with Javascript

javascript
prompt-engineering
responsive-design
performance
Nikita BarsukovbyNikita Barsukov·Dec 18, 2024
TLDR

To change CSS through JavaScript, you work with the element.style.cssProperty. If you're managing simple tasks, this method does the job excellently. Your target is our trusted paragraph with ID 'myPara'? Let's change its text color:

//When JavaSript walks into a bar, even the text turns red with laughter! document.getElementById('myPara').style.color = 'red';

Changing a CSS property containing hyphens, like font-size, turns hyphenated words into camelCase. Here's how we affect the fontSize:

//And then JavaScript said, "Let there be a bigger font!" And there was a bigger font. document.getElementById('myPara').style.fontSize = '20px';

But when it comes to manipulating non-inline styles or changes across multiple elements letting JavaScript delve into the stylesheet itself eases your work.

Diving into stylesheets

JavaScript gives you access to all stylesheets linked or embedded in your document through document.styleSheets and presents a more powerful approach to adjust CSS rules:

function modifyRule(selector, prop, value) { Array.from(document.styleSheets).some(sheet => { return Array.from(sheet.cssRules).some(rule => { if(rule.selectorText === selector){ rule.style[prop] = value; return true; } } )}) } //Our JavaScript commando is going style hunting. Be very, very quiet!

The modifyRule function above is your new stylesheet ninja, deftly finding a rule with the selector you specify and changing its property-value pair.

Adding new rules on-the-fly

Creating a new stylesheet on-the-fly lets you add or modify rules without affecting existing styles. Here's how:

//Meet JavaScript's stylist on demand let sheet = document.createElement('style'); document.head.appendChild(sheet); sheet.sheet.insertRule('body { background-color: yellow; }', 0);

In these three lines, we've spun a new stylesheet and outfitted it with a wholesome "sunshine yellow" rule. Yes, CSS can be as fast as that!

Checking for browser compatibility

Although style manipulation is a fun aspect of JavaScript, touching on cross-browser compatibility can feel like walking into a minefield of gotchas. The cssRules vs. rules split signals the IE/non-IE divide.

For Firefox 25+, CSSStyleRule.style provides a useful function:

if('CSSStyleRule' in window) { //Pssst! Firefox users, this one's for you! document.styleSheets[0].insertRule(selector+' { '+property+': '+value+'; }', 0); }

Adding "!important" can keep your JavaScript changes on top:

rule.style.setProperty('color', 'blue', 'important'); //Ladies and gents, I present to you blue... in its most important avatar!

Interactive Style Changes

Enrich user interactions by dynamically changing styles in response to events. This way:

document.getElementById('interactiveButton').addEventListener('mouseover', function() { modifyRule('.dynamicText', 'color', 'green'); //We can't make you Hulk, but hey, green text on mouseover sounds quite super too! });

An on-demand styling whim now turns our text green on a button mouseover.

Templating with specificity

Potential conflicts from JavaScript style changes can be tamed by acknowledging the CSS specificity hierarchy. It goes like this:

  1. Inline styles (highest priority)
  2. IDs
  3. Classes, pseudo-classes, attribute selectors
  4. Elements, pseudo-elements

Performance considerations

Performance pitfalls may arise from multiple DOM or style changes. Solve this by:

  • Grouping DOM updates.
  • Limiting recalculations.
  • Favoring class changes over direct style manipulation.