Mustapha GANGA
Mustapha GANGA

Reputation: 833

How to clone Style element with its cssRules?

I have a style tag with css properties added with insertRule function.

I tried Element.cloneNode(tree), but it does not contain the cssRules

// Add a style tag to head
var style = document.createElement("style");
style.id = "style",
style.type = "text/css",
document.head.appendChild(style);

// Insert some stylesheet rules
var sheet = style.sheet;
sheet.insertRule("p {background-color: red}", sheet.cssRules.length);
sheet.insertRule("p {color: white}", sheet.cssRules.length);
console.log(style.sheet); //Display an object with Css rules

// Try to clone
var styleClone = style.cloneNode(true);
console.log(styleClone.sheet); //Display null !

I expect styleClone.sheet to be equal to style.sheet

Upvotes: 3

Views: 2483

Answers (2)

Atsushi
Atsushi

Reputation: 361

Cloned node doesn't get its own sheet property (or CSSStyleSheet object) until it is added to be part of the document <head> or <body>

We can give styleClone variable it's own sheet by inserting it to the head like the code is doing for style variable!

Here's what I got

// Add style a tag to head
var style = document.createElement("style");
style.id = "style",
style.type = "text/css",
document.head.appendChild(style);

// Insert some stylesheet rules
var sheet = style.sheet;
sheet.insertRule("p {background-color: red}", sheet.cssRules.length);
sheet.insertRule("p {color: white}", sheet.cssRules.length);
console.log(style.sheet); //Display an object with Css rules

// Try to clone
var styleClone = style.cloneNode(true);
console.log(styleClone.sheet); //Display null !

// Added
document.head.appendChild(styleClone);
// Copy all rules from style variable
for (var i = 0; i < style.sheet.rules.length; i++) {
  styleClone.sheet.insertRule(style.sheet.rules[i].cssText)
}

Upvotes: 3

Orange Orange
Orange Orange

Reputation: 1981

I don't know why you're trying to do it that way. My example is way more easier and banal but it does what you're asking for (if I got it right).

    var style = document.createElement("style");
    style.id = "style",
    style.type = "text/css",
    document.head.appendChild(style);
    // create the clone element
    var clone = document.createElement("style");
    clone.id = "clone",
    clone.type = "text/css",
    document.head.appendChild(clone);
    // set the original style as you want
    style.innerHTML = "p {color:red}";
    // copy the same content of style into clone
    clone.innerHTML = style.innerHTML;
    

Insert this code into a script and load it via onload or whatever you want.

Upvotes: -2

Related Questions