1

I'm trying to parse a SVG element from a string and render it into the DOM but when I parse as image/svg+xml, the <svg> gets appended into the DOM in some strange way that does not render it (at least in Firefox). When I parse as text/html, it does render but adds an undesired xmlns attribute.

Is there some way to still parse as image/svg+xml (because that's what it is) while having it render? I tried document.adoptNode but it did not help.

This does not render:

const svg = '<svg viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.75 2a.75.75 0 0 1 .75.75V7h4.25a.75.75 0 1 1 0 1.5H8.5v4.25a.75.75 0 1 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2z"/></svg>';
const parser = new DOMParser();
const doc = parser.parseFromString(svg, 'image/svg+xml');
document.body.appendChild(doc.documentElement);

This renders, but includes undesired xmlns attribute:

const svg = '<svg viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M7.75 2a.75.75 0 0 1 .75.75V7h4.25a.75.75 0 1 1 0 1.5H8.5v4.25a.75.75 0 1 1-1.5 0V8.5H2.75a.75.75 0 0 1 0-1.5H7V2.75A.75.75 0 0 1 7.75 2z"/></svg>';
const parser = new DOMParser();
const doc = parser.parseFromString(svg, 'text/html');
document.body.appendChild(doc.body.firstChild);
silverwind
  • 3,296
  • 29
  • 31
  • 1
    why is an xmlns attribute undesirable? Note the first case should render if you actually use the proper xmlns attributes. – Robert Longson Apr 05 '21 at 20:26
  • Just checked your code in a fiddle: https://jsfiddle.net/mrovinsky/wj1rz2ub I see rendered without xmlns attribute – Michael Rovinsky Apr 06 '21 at 08:35
  • I see that the first example renders when adding the `xmlns`. I just thought it undesirable because in HTML (the target document), the attribute is optional and I prefer to keep things minimal. So I guess that answers the question already. `xmlns` is not optional when parsing for the SVG namespace, but is for the HTML namespace. – silverwind Apr 06 '21 at 22:30

1 Answers1

-1

The issues comes down to the xmlns attribute which is required when parsing for the SVG mime type but optional in the HTML one, as described in https://stackoverflow.com/a/18468348/808699.

Given that SVG is considered a foreign element in HTML, it's prefered to parse it as text/html if one wants to omit the xmlns attribute.

silverwind
  • 3,296
  • 29
  • 31