SomeKittens
SomeKittens

Reputation: 39522

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?

Upvotes: 28

Views: 27174

Answers (2)

user4231600
user4231600

Reputation:

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.

Upvotes: 21

bluetiger9
bluetiger9

Reputation: 728

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

Upvotes: 40

Related Questions