Accessing a DOM object defined in an external SVG file

Spread the love

Question Description

SVG standard allows to use and refer external SVG files.

I have a file circle.svg that defines a circle object with id “the_circle”.
From the main SVG file I am able to include this circle and animate it, using SVG linking.

I would also like to access the same circle object via javascript, how can I do this ?
What is the javascript equivalent of xlink:href="url(#the_image)#the_circle" ?

Using document.getElementById('the_image') I can only access the SVGImageElement but not the objects defined inside the included SVG.





  

  

Practice As Follows

It seems like the “right” way to do this would actually be to use an SVG “use” element, rather than an image. The reason for this is that the DOM interface of the SVG use element specifies a property “instanceRoot”, which allows you to get the root of the “instance tree” corresponding to that use element: http://www.w3.org/TR/SVG/struct.html#InterfaceSVGUseElement

So, you would end up with a solution that looks something like the following:
circle.svg:




    

Document which uses the svg root node of circle.svg:



 

    

Unfortunately, though, while Firefox supports use of the use element with external documents, there’s currently a bug in Webkit which does not allow this: https://bugs.webkit.org/show_bug.cgi?id=12499

Also, Firefox does not seem to implement the instanceRoot property for use elements.

So, it seems you may need to work around the limitations of current SVG implementations. The way I would recommend doing this is to use XMLHttpRequest to download the document to which you would like to link, and import the DOM of the downloaded document into your host document’s DOM. The following code implements this, and works in Firefox, Opera and Chromium:



 

    

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.