test.php
is a SVG object that's being generated with PHP.
<object data="test.php" type="image/svg+xml" id="SVG" /> <script> var mySVG = document.getElementById("SVG"); var svgDoc = mySVG.contentDocument;
svgDoc
is null. (and so I can't access the elements of the svg via JS.) It should work, looking at this question. What am I doing wrong? How can I get the contentDocument
of my SVG?
Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data.
SVG documents in web browsers support the core DOM methods defined for all XML and HTML elements. For the most part, these core methods are the easiest and best-supported way to control the SVG DOM.
The simplest way to make a portion of an SVG clickable is to add an SVG hyperlink element to the markup. This is as easy as wrapping the target with an <a> tag, just as you would a nested html element. Your <a> tag can surround a simple shape or more complex paths. It can surround a group of SVG elements or just one.
You need to wait until the SVG is loaded and than you can access the contentDocument:
var mySVG = document.getElementById("SVG"); var svgDoc; mySVG.addEventListener("load",function() { svgDoc = mySVG.contentDocument; alert("SVG contentDocument Loaded!"); }, false);
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