2

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.

Shai UI
  • 50,568
  • 73
  • 204
  • 309

2 Answers2

1

Unfortunately, unlike the iframe element, when you reference your SVG from another file, it's not loaded as a document you can manipulate.

grammar31
  • 2,000
  • 1
  • 12
  • 17
1

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:

function loadSVGInline()
{
    var SVGFile="mySVG.svg"
    var loadXML = new XMLHttpRequest;
    function handler(){
        if(loadXML.readyState == 4 && loadXML.status == 200)
        {
            svgDiv.innerHTML=loadXML.responseText
        }
    }
    if (loadXML != null){
        loadXML.open("GET", SVGFile, true);
        loadXML.onreadystatechange = handler;
        loadXML.send();
    }
}
Francis Hemsher
  • 3,478
  • 2
  • 13
  • 15
  • this basically has the security limitions of accessing contentDocument as noted above. Which doesn't help me much as I'm not using this on a server.. – Shai UI Apr 10 '14 at 18:39
  • I guess I don't understand. XMLHttpRequest can load a file the same as the data="myfile.svg" file request for the object. – Francis Hemsher Apr 10 '14 at 20:35