Dynamically Changing an Injected CSS Class …Good? …Bad?

Dynamically Changing an Injected CSS Class ...Good? ...Bad?

I found a 'need' to modify a CSS Class that I inject into the header vis javascript. Because I build the class dynamically and inject it into the header, I found it easy to modify the Class's text and put it back into the CSS Class definition whereby changing it.

By inject, I mean: var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = ".classname { ...css text... }"; document.getElementsByTagName('head')[0].appendChild(style);

and by modifying the Class, I mean simply changing the text: { ...css text... }

and putting it back: style.innerHTML = ".classname { ...new css text... }";

I really have not seen this done before and am asking if there is a reason that this is not done more often? ...that is, "is this a bad practice?" and perhaps "are there browser/device combinations where this may not work?"

Thank you.

Answers:

Answer

This is a bad practice. A CSS class should have a single definition. Modifying the class conditionally makes your code hard to follow and hard to maintain.

The correct way would to be create a separate CSS class for each condition, or modify the DOM directly using Javascript.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.