Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Load svg from file using JavaScript

I have searched the web but the answers showing embedding the SVG into the HTML using <object>, <img>, etc. What I want to do is open a large SVG file that contains lots of images, find the image I need, and show only that image on the page. How can I do that?

File structure is:

  • directory
    • index.html
    • script.js
    • images.svg

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A few steps:

  1. Use the Fetch API to get the image data.
  2. Use a DOM parser to parse the XML into a document.
  3. Find the SVG subset you want. (You didn’t show us your XML, but this is likely as simple as document.querySelector().)
  4. Create an SVG element. (This is actually a bit tricky due to the namespace. See also: JavaScript createElementNS and SVG)
  5. Append it to the relevant element on your page.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading