I'm loading an SVG through an object tag and need to access SVG's elements (to manipulate them). How can I do that?
Here're partial solutions I'm aware of:
Use SVG params where you set params for the object tag and parameterize attributes of the SVG elements. This works great for things like rect, but not for g (group) that I need to move (that takes a "transform" that can't be parameterized, looks like).
I've seen suggestions to use contentDocument or getSVGDocument() on the object element that you get through getElementById("yoursvgid"). Unfortunately, neither is working - and yes, I'm calling these after the SVG is loaded.
I can't believe there is no simple/reliable way to access SVG elements from within HTML (searched here/web) - would really appreciate help on this!
Alternatively, if there is some way to call a function defined inside SVG from within HTML (or vice versa), that'd do it too. In general, any way to communicate between SVG and HTML.
Here's a technique I have used successfully, mentioned in the (very good) O'Reilly "SVG Essentials" book:
Add JavaScript code to your SVG document itself and handle the load event on the root svg element.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)">
<script type="text/ecmascript" xlink:href="svgScript.js" />
In this svgScript.js load event handler, write out whatever you need to expose to the HTML-side script through the built-in parent
variable.
function init(evt) {
svgDocument = evt.target.ownerDocument;
parent.theSvgDocument = svgDocument;
}
Back in your HTML-side script, you can now directly access and use this reference.
var svgDocument = theSvgDocument;
In this example we expose the SVG Document object but you could pass on any object or a function. In my project I actually exposed some kind of controller object reference so that my SVG-side script contains all the logic for manipulating the SVG document, and the HTML-side script merely grabs this controller object and calls public methods on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With