/    Sign up×
Community /Pin to ProfileBookmark

Changing CSS classes for all elements

Is it possible to adjust the definition of a style so that it is immediately reflected across all elements?

For example, say I have a CSS class defined as such:

.mystyle
{
color:blue;
}

And I have 20 elements on my page that use this style. Can I use javascript to change the color in the .mystyle to red, and so change the color of all the elements simultaneously and without having to reference the .style.color for each one? I haven’t found any way to reference CSS styles this way.

Thanks 😮

.Rye

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@mrhooOct 02.2006 — You can manipulate styleSheet objects in IE and firefox, with different syntax.

This method is a quick and dirty that works on IE,Mozilla and Opera:

[CODE]function newStyle(str,med,t){
var pa= document.getElementsByTagName('head')[0] ;
var el= document.createElement('style');
el.type= 'text/css';
el.media= (med)? med: 'screen';
if(t) el.title=t;
if(window.attachEvent && el.styleSheet){//IE only
el.styleSheet.cssText= str;
}
else{
str=document.createTextNode(str)
el.appendChild(str);
}
pa.appendChild(el);
return el;
}[/CODE]


newStyle('.mystyle{color:blue}','screen');

You can identify the style element with a unique title and

replace it with subsequent changes, rather than adding more elements.

It might be simpler to loop through elements with the "myStyle" className and set the style color for each.
×

Success!

Help @ryeterrell spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...