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" />
    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?



Not sure this is an answer, but it worked for me. I had the same problem and svgObject was returning null:

var svgObject = document.getElementById('svgObject').contentDocument;

Then it occurred to me that I was running my html page locally: file:///C:/wwwroot/App_dev/OverLay/Overlay03.html

Running it from the server: http://localhost:62551/App_dev/OverLay/Overlay03.html

It worked flawlessly and svgObject returned its content, then I could get the div inside it.


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);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.