user783146
user783146

Reputation: 1565

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?

Upvotes: 46

Views: 40230

Answers (5)

Syed
Syed

Reputation: 16543

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

Upvotes: 2

jDelforge
jDelforge

Reputation: 126

If you’re using a back end language that can go fetch the file and insert it, at least you can clean up the authoring experience. Like:

<?php echo file_get_contents("kiwi.svg"); ?>

A little PHP-specific thing here… it was demonstrated to me that file_get_contents() is the correct function here, not include() or include_once() as I have used before. Specifically because SVG sometimes is exported with that as the opening line, which will cause the PHP parser to choke on it.

(Information taken out of CSS-tricks)

Upvotes: 0

Anton Medvedev
Anton Medvedev

Reputation: 3668

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

Upvotes: 1

Erik Dahlstr&#246;m
Erik Dahlstr&#246;m

Reputation: 61046

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.

Upvotes: 43

nrabinowitz
nrabinowitz

Reputation: 55678

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

Upvotes: 17

Related Questions