How to access SVG elements with Javascript How to access SVG elements with Javascript javascript javascript

How to access SVG elements with Javascript


Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?

Definitely.

If it is possible, what's the technique?

This annotated code snippet works:

<!DOCTYPE html><html>    <head>        <title>SVG Illustrator Test</title>     </head>    <body>        <object data="alpha.svg" type="image/svg+xml"         id="alphasvg" width="100%" height="100%"></object>        <script>            var a = document.getElementById("alphasvg");            // It's important to add an load event listener to the object,            // as it will load the svg doc asynchronously            a.addEventListener("load",function(){                // get the inner DOM of alpha.svg                var svgDoc = a.contentDocument;                // get the inner element by id                var delta = svgDoc.getElementById("delta");                // add behaviour                delta.addEventListener("mousedown",function(){                        alert('hello world!')                }, false);            }, false);        </script>    </body></html>

Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg must be hosted on the same domain as the .html file, otherwise the inner DOM of the object will be inaccessible.

Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat


In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {    //alert("Document loaded, including graphics and embedded documents (like SVG)");    var a = document.getElementById("alphasvg");    //get the inner DOM of alpha.svg    var svgDoc = a.contentDocument;    //get the inner element by id    var delta = svgDoc.getElementById("delta");    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);});


If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.