1

I've been struggling for... hours on a simple problem even though it seems to have been described here :How to access SVG elements with Javascript

I can't access elements of an external svg file loaded in a embed tag, even if I wait for the div or the whole window to load (I've tried several "load listeners")

I've simplified my html file into those fewlines to show you the issue :

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Desperate demo</title>   
</head>
<body>

<div id="content">
    <embed class="emb" id="maptest" type="image/svg+xml" src="star.svg">
</div>
<script type='text/javascript'>
window.onload = initAll;
function initAll(){
    var mySVG = document.getElementById("maptest");
    var svgDoc = mySVG.contentDocument;
    console.log(svgDoc);
}
</script>
</body>
</html>

Basically, the log returns "null" or "undefined" on contentDocument property call, as if there was no svg at all loaded in the DOM.

Can you see what did I miss ? It doesn't work either if I write the whole svg tag in my html instead of calling an extern file...

Community
  • 1
  • 1
Cedric B
  • 13
  • 3

1 Answers1

2

Try getSVGDocument() and see if it helps you:

window.onload = initAll;
function initAll(){
    var mySVG = document.getElementById("maptest");
    console.log(mySVG);
    var svgDoc = mySVG.getSVGDocument();
    console.log(svgDoc);
}
J S
  • 1,068
  • 6
  • 7
  • Oh yes it seems to work ! Strange because I'm pretty sure I tried it on an other version. Anyway, thank you very much ! Could you maybe teach me the difference between those two guys, getsvgdocument() and contentDocument ? – Cedric B Sep 28 '16 at 07:27
  • @CedricB Glad it worked. As far as I know their usage should be equivalent, for getSVGDocument you just need to be sure an svg is there. contentDocument should work for – J S Sep 28 '16 at 07:41
  • In my case, I was appending the svg as an object via jquery and trying to do this with the jquery element[0] - which apparently wasn't reaching the actual element which became appended to my html. Referencing the new id of the appended element worked though. – Vasily Hall May 08 '20 at 15:03