Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript accessing inner DOM of SVG

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?

like image 802
SomeKittens Avatar asked Jul 11 '12 14:07

SomeKittens


People also ask

Can SVG integrate with JavaScript?

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.

Is SVG part of DOM?

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.

How do I create a SVG link?

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.


1 Answers

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); 
like image 139
bluetiger9 Avatar answered Sep 23 '22 08:09

bluetiger9