tags:

views:

40

answers:

1

I have a javascript variable that basically looks like this:

my_svg_image = '<circle cx="227.58331298828125" cy="102" r="3" style="fill:black;stroke-width:0" />';

It was loaded from my database. Is there a way I can parse that string and add it to the DOM with Javascript? I have svgweb set up, but don't see how I can get it to parse this string. Are there other libraries that might help?

A: 

have you tried javascript's innerHTML property?

edit: You can only use innerHTML property for html elements, so you can use a string containing a whole svg image to add it to an html element. But you cannot add a svg element to an existing svg element.

Example:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"
"http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"&gt;
   <head>
      <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8"/>
   <script type="text/javascript">
   <![CDATA[    
    function test() {
        var newsvg = document.getElementById("svg-wrapper");
        var svgstr = '<svg:svg height="300" width="700" id="svg-container"><svg:circle cx="150px" cy="100px" r="30px" /></svg:svg>';
        newsvg.innerHTML = svgstr;
    }   
   ]]>
   </script>
   <title>SVG DOM</title>
 </head>
 <body>
    <div id="svg-wrapper"></div>
    <input type="button" onclick="javascript:test();" value="generate svg"/><br/>
 </body>
 </html>

If you want to add a circle to existing inline SVG, you have to add it using DOM methods (and the prbably first parse your string to extract the needed attribute values).

räph
More descriptive...what tag should I add it within?
Colin
i edited my answer to make the use of innerHTML clearer
räph