4

I'm trying to parse SVG from string with DOMParser. If SVG string has attribute xmlns, then element renders correctly. Otherwise browser don't render it, but element exist in DOM (it's visible in dev tools).

In this example renders only first element: https://jsfiddle.net/Severn101/jatkyvw7/

var circle1 = '<circle cx="25" cy="25" r="25" xmlns="http://www.w3.org/2000/svg" />';
var circle2 = '<circle cx="25" cy="25" r="25" />';
var svgElement = document.getElementById('svg');

var parser = new DOMParser();
var doc1 = parser.parseFromString(circle1, "image/svg+xml").documentElement;
var doc2 = parser.parseFromString(circle2, "image/svg+xml").documentElement;

svgElement.appendChild(doc1);
svgElement.appendChild(doc2);

Why is this happening and how parse svg string without mlns attribute?

severn101
  • 41
  • 2
  • The namespace is required when providing "image/svg+xml" files to a XML parser by standard: [Are SVG parameters such as 'xmlns' and 'version' needed?](https://stackoverflow.com/questions/18467982/are-svg-parameters-such-as-xmlns-and-version-needed) (First and second answers) – yuriy636 Aug 28 '17 at 18:26

1 Answers1

0

When you create the elements using DOMParser it's create them as an html element, not as svg element. That's why it's not displaying, even it's added to the DOM.

In the first circle you add a namspace. it's indicate that it is xml and it is why it's appear in your fiddle. (However you have same cx and cy for both circles, so even if they both will rendered you will see only one, since they will be on top of one another)

But if you have it as a String, why not just use innerHTML?

innerHTML=circle1 for replace, and innserHTML+=circle1 for append

var circle1 = '<circle cx="50" cy="25" r="25" fill="green"/>';
var circle2 = '<circle cx="100" cy="25" r="25" fill="red"/>';
var svgElement = document.getElementById('svg');
svgElement.innerHTML += circle1+circle2;
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 50" id="svg"></svg>
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29
  • "When you create the elements using DOMParser it's create them as an html element, not as svg element. That's why it's not displaying, even it's added to the DOM." Is there a workaround to this? – analytical_prat Sep 28 '21 at 10:22