What is the difference between SVGNode.outerHTML and XMLSerializer().serializeToString(SVGNode)?
The result seems to be the same.
Thank you in advance.
XMLSerializer will produce a valid XML markup, while outerHTML will only output HTML.
SVG in HTML is way more lax than when it's parsed as a standalone XML document. For instance, in HTML you can omit the xmlns="http://www.w3.org/2000/svg" on the root <svg>, as a standalone doc you can't. This is also true for any namespaced attributes, HTML doesn't have a concept of namespace. XMLSerializer will add it back to you, while outerHTML won't. Another minor difference is that in HTML, only void elements can omit their end tags. At parsing the HTML parser will also allow elements inside and <svg> node, but when you'll get the outerHTML, the serializer will add it back. The XMLSerializer won't.
const svgNode = document.querySelector("svg");
console.log("outerHTML", svgNode.outerHTML)
console.log("XMLSerializer", new XMLSerializer().serializeToString(svgNode))
<svg><rect width=30 height=30 /></svg>
Note that these points are important because if you want to load the generated string as an SVG image, only the one produced by the XMLSerializer will work:
const svgNode = document.querySelector("svg");
const outerImg = new Image();
outerImg.src = "data:image/svg+xml," + encodeURIComponent(svgNode.outerHTML);
document.body.append("outerHTML:", outerImg, document.createElement("br"));
const serializerImg = new Image();
serializerImg.src = "data:image/svg+xml," + encodeURIComponent( new XMLSerializer().serializeToString(svgNode));
document.body.append("XMLSerializer:", serializerImg, document.createElement("br"));
img, svg { vertical-align: top }
svg:<svg><rect width=30 height=30 /></svg><br>