Changing CSS Values with Javascript
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:
Changing a CSS property containing hyphens, like font-size, turns hyphenated words into camelCase. Here's how we affect the fontSize
:
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:
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:
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:
Adding "!important" can keep your JavaScript changes on top:
Interactive Style Changes
Enrich user interactions by dynamically changing styles in response to events. This way:
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:
- Inline styles (highest priority)
- IDs
- Classes, pseudo-classes, attribute selectors
- 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.
Was this article helpful?