How do you access the contents of an SVG file in an <img> element?

Say you have this in your HTML:

<img src='example.svg' />

How would you access the contents ( ie. <rect>, <circle>, <ellipse>, etc.. ) of the example.svg via JavaScript?

I'm pretty sure this isn't possible. The external SVG is not part of the DOM in the way an inline SVG is, and I don't believe you can access the SVG DOM tree from the loading document.

What you can do is load the SVG as XML, using an AJAX request, and insert it into the DOM as an inline SVG you can then walk and manipulate. This D3 example demonstrates the technique. I think the d3.xml() function used here is more or less equivalent to jQuery's $.ajax() with dataType: "xml".

If you are using inlining of SVG into CSS url(data:...) or just using url(*.svg) background, you can embed them into DOM with svg-embed.

Support Chrome 11+, Safari 5+, FireFox 4+ and IE9+.

No, not possible but you can just Convert <img> to <svg> as mentioned HERE and you can just access the nodes in svg in DOM.

It's not possible to get the DOM of a referenced svg from the img element.

If you use <object>, <embed> or <iframe> however then you can use .contentDocument (preferred) to get the referenced svg, or .getSVGDocument which may be more compatible with old svg plugins.

Here's an example showing how to get the DOM of a referenced svg.