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

Solution 1:

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.

Solution 2:

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".

Solution 3:

No, not possible but you can convert <img> to <svg> as mentioned HERE (same code available below) and you can access the nodes of svg in the DOM.

<script type="text/javascript">

    $(document).ready(function() {
        $('#img').each(function(){
            var img         = $(this);
            var image_uri   = img.attr('src');

            $.get(image_uri, function(data) {
                var svg = $(data).find('svg');
                svg.removeAttr('xmlns:a');
                img.replaceWith(svg);
            }, 'xml');

        });
    });
</script>


<img id='img' src="my.svg" />