October 25, 2024
Chicago 12, Melborne City, USA
CSS

Create, modify, disable multiple CSS rules by ID with JavaScript


Abstract

I’m trying to figure out a way to use JavaScript to dynamically create CSS rules on a page, modify them, and disable them. The rules would come in "packages" with an ID and a group of one or more CSS rules which may overlap.

Example and Data

/*ID: something*/
div#foobar {display:none;}

/*ID: blah*/
input {background:red;}
div.password {width:100px;}

/*ID: test*/
div.password {width:200px;}

The rules are in an associative-array that contains the data, such as:

myrules["something"] = "div#foobar {display:none;}";
myrules["blah"]      = "div.password {width:100px;} input {background:red;}";
myrules["test"]      = "div.password {width:200px;}";

“Question”

Now I need a way to add the defined rules to the page with a way to toggle them using the IDs.

Requirements

The main issues the current attempts (below) have run into are:

  • Adding CSS rules via CSS syntax (ie, not JavaScript object names, so background-color, not .backgroundColor)
  • Being able to enable and disable the rules
  • Being able to access the rules via a string ID, not a numeric index
  • The rules should be bunched in a single stylesheet object or element since there can be a LOT of rules, so creating a separate stylesheet element for each would be impractical

Attempts (what I’ve already tried)

I’ve looked at several different ways from document.styleSheets to .sheet.cssRules[], from .innerHTML to insertRule(). I’ve become dizzy from trying to figure out what’s what; it’s such a quagmire, with poor examples. Sometimes I manage to use one technique to accomplish one aspect of it, but then another aspect won’t work. I can’t find a solution that satisfies all of the aforementioned requirements.

And searches are difficult because of the ambiguous nature of phrasing leading to incorrect search-results.

Surely there has to be an efficient way to do this, right? 🤨



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video