This question already has an answer here:
- How to access SVG elements with Javascript 3 answers
- D3: Select and alter external SVG? 1 answer
I find that if I embed svg in my html then I can access the id's simply:
<svg width="100" height="100">
<circle id='myCircle' cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
Javascript:
$('#myCircle').css('fill','red'); // works fine
But if I load this svg file externally:
<object id='myfile' data="myfile.svg" type="image/svg+xml">
</object>
(and assuming this svg contains the same id/content as above) I cannot do:
$('#myCircle').css('fill','red'); // doesn't work anymore
so I'm wondering how I can access the id's of externally loaded .svg files?
Update:
I tried
var doc = $('#piano')[0].contentDocument; doc.getElementById('#myCircle);
But I get, (I'm using Chrome)
SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement': Blocked a frame with origin "null" from accessing a cross-origin frame.
Unfortunately, unlike the
iframe
element, when you reference your SVG from another file, it's not loaded as adocument
you can manipulate.If you want DOM access to your svg, the best way is to load svg files inline for your HTML5 document, is to create a DIV id="svgDiv", and use svgDiv.innerHTML to accept
XMLHttpRequest.responseText
Below is an example: