I am trying to dynamically display some SVG content. This content is stored as a string in my data source. An example string would look like the following:
Found a partial answer here and reproduced below. Note, that this approach forces you to build the root tags and attributes yourself in javascript instead of just loading the whole svg document that you have in your question's example.
Dynamically creating an SVG Root element is similar for direct embedding into a web page. You don't have to create a SCRIPT tag like you would if you were direct embedding the SVG on page load:
Instead, you follow a process similar to the above:
// create SVG root element
var svg = document.createElementNS(svgns, 'svg'); // don't need to pass in 'true'
svg.setAttribute('width', '300');
svg.setAttribute('height', '300');
// create an example circle and append it to SVG root element
var circle = document.createElementNS(svgns, 'circle');
svg.appendChild(circle);
Must use a callback to know when SVG is appended to page (this is slight divergence from standard). The following are supported ways to do this:
svg.addEventListener('SVGLoad', function() {
svg = this; // this will correctly refer to your SVG root
alert('loaded!');
}, false);
// also supported:
svg.onsvgload = function() {
alert('loaded!');
}
Now append the SVG root to our document
svgweb.appendChild(svg, document.body); // note that we call svgweb.appendChild
Note in the above code that we have to use an event listener to know when the SVG root is finished loading into the page; this is a slight divergence from the standard necessary for SVG Web's magic.
The parent that you attach either your SVG root must already be attached to the real DOM on your page (i.e. it can't be disconnected from the page).