Search code examples
javascriptjquerysvgstylesheet

Change SVGs 'style' element in IE/Edge


I have a SVG which contains a bit of css. I want to change the style element in this SVG, with javascript, but in IE/Edge you can;t change the style element with .innerHTML. Instead, you need .styleSheet.cssText, but I cant get it to work in my SVG.

This works in non-IE browsers, to get and set the value:

var style  = document.getElementById('example').contentDocument.querySelector("style");
style.innerHTML = style.innerHTML.replace('foo', 'bar')

The SVG (simplified):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 540 494.08">
    <defs>
        <style id="SvgStyleSheet">
            .someClass{}
        </style>
        <!-- Some more definitions -->
    </defs>
    <!-- SVG elements here -->
</svg>

How do I get and set the style in this SVG?


Solution

  • Turns out I was very very close with .styleSheets.cssText, had to use it slightly different.

    In order to keep it working in IE/Edge, Firefox, Android, Chrome and iPhone's browser, I had to implement both.

    var svgDOC = document.getElementById('idOfSVG').contentDocument;
    
    style = svgDOC.styleSheets[0];
    // IE/Edge
    if( typeof style.cssText !== "undefined" ){
        style.cssText = style.cssText.replace('foo', 'bar');
    }
    // Non IE/Edge:
    else{
        var style = svgDOC.querySelector("style");
        style.innerHTML = style.innerHTML.replace('foo', 'bar');
    }
    

    Note:

    It's worth noting that Firefox and other return the actual innerHTML as it is written. If you have no newlines, no newline are in the result:
    .example1{boo:bar;}

    IE and Edge however will return a parsed result.

    .example1 {
        boo: bar;
    }