Luke Luke - 12 days ago 10
Javascript Question

Is it possible to get the XML of an SVG image using JavaScript?

My goal is to load an SVG image in JavaScript and have it both as an image and the underlying SVG XML.

I can load the image like...

var myImage = new Image();
myImage.src = "cat.svg";


Now after I have the image, how can I access the underlying XML that makes up the SVG image?

The only solution I've come up with is to load it again via ajax:

$(myImage).one("load", function(){
$.ajax({
url : "cat.svg",
cache : true,
dataType : "xml"
}).fail(function( jqXHR, textStatus, errorThrown ) {
console.error("Ajax failure loading image.");
}).done(function( data, textStatus, jqXHR ){
console.log("Got the image's SVG XML:", $(data).find('svg'));
});
});


But I feel like there might be a better way to do this.

Answer

There is no way to extract the image source from the Image object.

The AJAX solution included in your question is the only way to obtain the source.

If you want to only load the image once, then perhaps you could fetch it first using AJAX, and then use the fetched XML to render the image (e.g. adding to the document as inline SVG, or setting the source to a data: or Blob URL).