Javascript adding css rules

CSSStyleSheet: addRule() method

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The obsolete CSSStyleSheet interface’s addRule() legacy method adds a new rule to the stylesheet. You should avoid using this method, and should instead use the more standard insertRule() method.

Syntax

addRule(selector, styleBlock, index) 

Parameters

A string specifying the selector portion of the CSS rule. The default is the string undefined .

A string indicating the style block to apply to elements matching the selector . The default is the string undefined .

An optional index into the stylesheet’s CSSRuleList at which to insert the new rule. If index is not specified, the next index after the last item currently in the list is used (that is, the value of cssStyleSheet.cssRules.length ).

Return value

Note that due to somewhat esoteric rules about where you can legally insert rules, it’s possible that an exception may be thrown. See insertRule() for more information.

Usage notes

This method is implemented by browsers by constructing a string using the template literal `$>` , then passing it into the standard insertRule() method.

Therefore, given existing code such as the following:

You can rewrite this to use the more standard insertRule() like this:

.insertRule(`$selector> $styles>>`, 0); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

CSSStyleSheet: insertRule() method

The CSSStyleSheet.insertRule() method inserts a new CSS rule into the current style sheet.

Note: Although insertRule() is exclusively a method of CSSStyleSheet , it actually inserts the rule into CSSStyleSheet.cssRules — its internal CSSRuleList .

Syntax

insertRule(rule) insertRule(rule, index) 

Parameters

A string containing the rule to be inserted. What the inserted rule must contain depends on its type:

  • For rule-sets, both a selector and a style declaration.
  • For at-rules, both an at-identifier and the rule content.

A positive integer less than or equal to stylesheet.cssRules.length , representing the newly inserted rule’s position in CSSStyleSheet.cssRules . The default is 0 . (In older implementations, this was required. See Browser compatibility for details.)

Return value

The newly inserted rule’s index within the stylesheet’s rule-list.

Exceptions

Thrown if rule cannot be inserted at index 0 due to some CSS constraint.

Thrown if more than one rule is given in the rule parameter.

Thrown if trying to insert an @import at-rule after a style rule.

Thrown if rule is @namespace and the rule-list has more than just @import at-rules and/or @namespace at-rules.

Examples

Inserting a new rule

This snippet pushes a new rule onto the top of my stylesheet.

Function to add a stylesheet rule

/** * Add a stylesheet rule to the document (it may be better practice * to dynamically change classes, so style information can be kept in * genuine stylesheets and avoid adding extra elements to the DOM). * Note that an array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. * @param rules Accepts an array of JSON-encoded declarations * @example addStylesheetRules([ ['h2', // Also accepts a second argument as an array of arrays instead ['color', 'red'], ['background-color', 'green', true] // 'true' for !important rules ], ['.myClass', ['background-color', 'yellow'] ] ]); */ function addStylesheetRules(rules)  const styleEl = document.createElement("style"); // Append element to document.head.appendChild(styleEl); // Grab style element's sheet const styleSheet = styleEl.sheet; for (let i = 0; i  rules.length; i++)  let j = 1, rule = rules[i], selector = rule[0], propStr = ""; // If the second argument of a rule is an array of arrays, correct our variables. if (Array.isArray(rule[1][0]))  rule = rule[1]; j = 0; > for (let pl = rule.length; j  pl; j++)  const prop = rule[j]; propStr += `$prop[0]>: $prop[1]>$prop[2] ? " !important" : "">;\n`; > // Insert CSS Rule styleSheet.insertRule( `$selector>$propStr>>`, styleSheet.cssRules.length, ); > > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Источник

How to Add CSS Rules to a Stylesheet with Javascript

You must be wondering what would be the real need to add CSS rules to a stylesheet with Javascript. A better way would be to just hard-code the CSS properties in the stylesheet? Or changing the CSS properties of the element with Javascript will also work?

Sometimes the requirement is such that there is no option, other than using Javascript to add CSS to a stylesheet.

One such case is the CSS keyframes rule. Consider the below CSS rule :

@keyframes outlightbox < 0% < height: 100%; top: 0px; >100% < height: 500px; top: 50px; >> 

You can obviously hard-code this CSS rule in a stylesheet. But what when you don’t know the value of top in advance? The value of top may be dependent on the initial position of the element, or can be only set after a particular event occurs, or some other complex case.

Adding the keyframes rule to an element with Javascript or jQuery is not possible.

// There is no such thing as this $("#element").css('keyframes', . ); 

In this case you have no option but to dynamically add the keyframes rule to a stylesheet using Javascript.

Animating a Lightbox with CSS & Javascript is a perfect example where you need to add CSS to a stylesheet dynamically.

Creating a New Stylesheet To Add CSS Rules

When dynamically creating CSS rules it is alays better to create a new stylesheet, and adding rules to it. It is because adding new CSS rules requires the index position where the new CSS rule is to be added. This is relatively simpler in a new stylesheet as the starting index is 0.

Creating and get reference to the new stylesheet with Javascript :

var element = document.createElement('style'), sheet; // Append style element to head document.head.appendChild(element); // Reference to the stylesheet sheet = element.sheet; 

Creating and get reference to the new stylesheet with jQuery :

$("head").append(''); var sheet = $("#new-animations").get(0).sheet; 

Using an Existing Stylesheet To Add CSS Rules

Although not recommended, but for the sake of showing it, here is how you can get reference to an existing stylesheet.

Assuming the stylesheet is of the form :

var sheet = document.getElementById('new-animations').sheet
var sheet = $("#new-animations").get(0).sheet

Adding a New CSS Rule in an Empty Stylesheet

You can insert a new CSS rule using the insertRule method.

var styles = '.new-animation '; // Add the first CSS rule to the stylesheet sheet.insertRule(styles, 0); 

The second parameter is the position or index of the CSS rule in the stylesheet. Index starts from 0. You cannot give an arbitrary position — the index of the new CSS rule must be after the index of the last CSS rule in the stylesheet.

The below code will give an error because after the 0th index is inserted, the code tries to insert new rule at the 2nd index.

// In an empty stylesheet, this is incorrect var styles1 = '.new-animation-1 '; sheet.insertRule(styles1, 0); var styles2 = '.new-animation-2 '; sheet.insertRule(styles2, 2); 

After the 0th position, the next position to be filled should be 1.

Another thing to note is that the newly injected CSS rules will probably not be seen when you use browser developer tools (Inspect Element). Nevertheless the CSS rules are being updated in the DOM.

Adding a New CSS Rule in an Existing Stylesheet

In an already existing stylesheet, CSS rules must be already present. So in order to append a new CSS rule, you must first find the length of CSS rules in the stylesheet, then use that to insert a new rule.

// The no of available CSS rules in the sheet // This will be the index of the next to-be-added rule var css_rules_num = sheet.cssRules.length; sheet.insertRule("#container < margin:5px; >", css_rules_num); 

Deleting an Existing CSS Rule

You can delete an existing CSS rule using the deleteRule method.

// This will delete the first rule from the stylesheet sheet.deleteRule(0);

Note that after deletion, the indexes of the rest of the CSS properties in the stylesheet will rearrange, just like deleting an element from an array will rearrange the array.

Updating an Existing CSS Rule

Very interestingly, updating a CSS rule at a paticular index is not possible. If you try to re-insert a new CSS rule at an occupied position, both the CSS rules will be updated in the DOM ! So take care.

So in order to update a CSS rule at a particular index, first delete the old rule and then insert the new rule.

Источник

Javascript Set CSS Set CSS styles with javascript

2. Global styles

 var style = document.createElement('style'); style.innerHTML = ` #target < color: blueviolet; >`; document.head.appendChild(style); 

global styles

3. CSSOM insertRule

 var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target '); 

insertRule

While it might look similar to the 2nd option, it’s definitely different.
As you can see in Chrome devtools, tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can’t be changed via devtools because Chrome doesn’t allow editing dynamic CSS styles. Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project’s issues.

4. Constructable Stylesheets (July 2019 update)

// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target '); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet]; 

More details are here.
This option is only valid for Chrome, so use with caution. Do you know other options to add styles with javascript? What is your preferred option these days? Thanks for reading!

Источник

Читайте также:  Javascript form data files
Оцените статью