27

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?

Community
  • 1
  • 1
SomeKittens
  • 38,868
  • 19
  • 114
  • 143

2 Answers2

39

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);
bluetiger9
  • 718
  • 7
  • 16
  • I also found (in addition to above) that it returned null when I was trying to access a svg via something like this: `data="../otherdir/images/mysvg.svg"` (at least locally, can't test online at the moment), though `data="images/mysvg.svg"` works. – Max Starkenburg May 01 '16 at 06:35
  • 3
    It does not work for me, I get always null –  May 24 '21 at 12:49
21

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.