Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
What is the difference between outerHTML and XMLSerializer().serializeToString(SvgNode)?

What is the difference between SVGNode.outerHTML and XMLSerializer().serializeToString(SVGNode)?

The result seems to be the same.

Thank you in advance.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!