2

I try to add a CSS style sheet to an SVG. So what I have is the following svg:

<svg>
  <defs id="mydefs">
  </defs>
  <rect class="myclass" x="10" y="10" width="20" height="20"/>
</svg>

And I would like to add a style sheet to this like:

<svg>
  <defs id="mydefs">
    <style type="text/css">
      .myclass {
        fill: red;
      }
    </style>
  </defs>
  <rect class="myclass" x="10" y="10" width="20" height="20"/>
</svg>

I tried

var defs = document.getElementById('mydefs');
var style = document.createElementNS("http://www.w3.org/2000/svg", 'style');
style.type = 'text/css';
style.insertRule('.myclass { fill: red; }', style.cssRules.length);
defs.appendChild(style);

But the insertRule (and cssRules) seems not to be supported. Here is the (not working) codepen:

https://codepen.io/anon/pen/EEoLqg

1 Answer 1

2

Works like this:

var defs = document.getElementById('mydefs');
var style = document.createElementNS("http://www.w3.org/2000/svg", 'style');
defs.appendChild(style);
style.type = 'text/css';
style.sheet.insertRule('.myclass { fill: red; }', style.sheet.cssRules.length);

(BTW, you can also just use the parent document's style sheet:)

var style = document.createElement('style');
document.head.appendChild(style);
style.type = 'text/css';
style.sheet.insertRule('.myclass { fill: red; }');

The above approaches don't show any CSS in the inspector. If you need that, you could try something like the following instead:

var defs = document.getElementById('mydefs');
var style = document.createElementNS("http://www.w3.org/2000/svg", 'style');
defs.appendChild(style);
style.innerHTML = '.myclass { fill: red; }';

Update: IE work-around as per Daniel's comment:

(The problem seems to be that IE does not support the .innerHTML for SVG elements.)

Use the .innerHTML of a <div> and set it to <svg><style>.myclass { fill: red }</style></svg> and then append all nodes in the div's .childNodes[0].childNodes[0] to the style element via:

Array.prototype.slice.call(div.childNodes[0].childNodes[0].childNodes).forEach(function(el) {
    element.appendChild(el);
});

where div is the <div> element.

Sign up to request clarification or add additional context in comments.

9 Comments

Hmm, where does the style go? I can't see it in the svg's <defs>. Am I missing something? Here is your code: codepen.io/anon/pen/EEoLqg
(I need the style to go into the svg since I am using it also as a standalone.)
Updated my post. Does this address what you were asking?
Yes, it does. At least in Firefox and Chrome. But for some reason IE 11 is not playing along.
Ah... Can't help with IE, sorry
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.