Skip to content Skip to sidebar Skip to footer

How To Embed Svg Styling With Javascript?

I'm trying to embed a CSS styling into a SVG content (like in this example) using JavaScript. The SVG itself is embedded into a HTML5 file. The purpose of style embedding is to sav

Solution 1:

You've two main bugs. Firstly, you need to create the style element in the SVG namespace i.e.

var style = document.createElementNS('http://www.w3.org/2000/svg', 'style');

Secondly you can't use <![CDATA[ in html it's an xhtml only thing so you want

var node = document.createTextNode('circle { fill: red; }');

Finally (and this bit is optional), the text/css attribute can be omitted if you wish. All of which gives you this

The specifications certainly do not tell you to use <![CDATA[ with html, but they do tell you to use it with xhtml and xml and SVG at one time was an xml only language. If you intend to have standalone svg files (which will be served as image/svg+xml) then you may need to put the <![CDATA[ back in.

Post a Comment for "How To Embed Svg Styling With Javascript?"