Parse SVG and add it to a svg element

Justin T. Watts

I have a service where I want to dynamically add SVG parts to a g element. This is what the service returns:

<g xmlns="http://www.w3.org/2000/svg" style="pointer-events: all;" opacity="1">
    <title style="pointer-events: inherit;">Layer 1</title>
    <path id="svg_1" style="pointer-events: inherit;" fill="none" stroke="#000000" stroke-width="5" d="M 231.5 122.5 C 230.5 122.5 221.666 124.214 214.5 125.5 C 201.667 127.803 184.514 129.581 173.5 131.5 C 167.508 132.544 164.077 131.928 158.5 136.5 C 155.219 139.19 152 144.469 151.5 156.5 C 151.375 159.497 150.696 163.582 151.5 167.5 C 153.031 174.96 161.804 180.205 170.5 189.5 C 177.762 197.263 185.013 204.954 192.5 212.5 C 200.981 221.048 208.5 226.5 214.5 232.5 C 219.5 237.5 224.834 240.27 227.5 244.5 C 230.219 248.814 230.986 251.324 231.5 253.5 C 231.96 255.447 231.5 258.5 231.5 260.5 C 231.5 262.5 228.786 265.712 226.5 268.5 C 224.707 270.687 221.213 274.151 217.5 277.5 C 213.17 281.405 207.5 283.5 203.5 285.5 C 199.5 287.5 195.676 289.986 193.5 290.5 C 190.58 291.189 188.5 292.5 187.5 292.5 L 186.5 292.5 L 186.5 293.5" />
    <path id="svg_2" style="pointer-events: inherit;" fill="none" stroke="#000000" stroke-width="5" d="M 39.5 35.5 C 40.5 35.5 42.5 35.5 45.5 35.5 C 47.5 35.5 50.5 35.5 52.5 35.5 C 54.5 35.5 56.5 35.5 57.5 35.5 L 58.5 35.5 L 59.5 35.5" />
    <path id="svg_3" style="pointer-events: inherit;" fill="none" stroke="#000000" stroke-width="5" d="M 40.5 95.5 C 40.5 97.5 39.8088 103.572 38.5 108.5 C 36.8767 114.613 35.5 117.5 35.5 119.5 C 35.5 121.5 34.5 122.5 34.5 123.5 L 33.5 123.5 L 33.5 124.5 L 33.5 125.5" />
    <path id="svg_6" style="pointer-events: inherit;" fill="none" stroke="#000000" stroke-width="5" d="M 81.5 176.5" /><path id="svg_7" style="pointer-events: inherit;" fill="none" stroke="#000000" stroke-width="5" d="M 79.5 167.5 C 79.5 170.5 80.1835 178.521 79.5 189.5 C 78.999 197.547 76.9069 204.357 75.5 211.5 C 73.75 220.385 72.663 227.522 71.5 235.5 C 70.6226 241.519 70.5 245.5 70.5 247.5 C 70.5 249.5 70.5 250.5 69.5 250.5 L 69.5 251.5 L 69.5 252.5" />
</g> 

The code I'm trying to use which has been modified many times is something to the affect of this:

function parseSVG(s, layer) {
    var div= $(s);
    for(var i = 0; i < div.children.length; i++) {
        layer.append(div.children[i]);
    }
}

layer is the g element s is the svg from above. The closest I can get is adding title then all the path elements at once inside of svg_1.

Robert Longson

You can use DOMParser to parse an XML string.

var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");

The <g> in your example will be doc.documentElement

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related