Reputation: 2518
I am trying to load an external SVG document into a simple web page so that I can use it as a basic chloropeth map. However, using <object data=""></object>
in the HTML results in the SVG loading as a subdocument.
Basically I am unable to query the SVG paths by ID using jquery (ex: $('#NY').css("fill", "red")
doesn't do anything). Obviously I can just cut and paste the actual SVG content into the HTML, but I'm curious if there is a way to get the SVG path stuff to load into the HTML document using <object>
or similar.
The HTML:
<object data="/static/metric/img/map_US.svg" type="image/svg+xml">
</object>
Here's a shot of the DOM using the console (notice the SVG stuff is inside a #document
subdocument!):
Upvotes: 2
Views: 1592
Reputation: 17720
I believe what you are looking for is getSVGDocument
or contentDocument
:
document.getElementById('thesvg').getSVGDocument().getElementById('theelement')
or
document.getElementById('thesvg').contentDocument.getElementById('theelement')
You probably want to test for both, I'm not quite sure what the compatibility is with various browsers at the moment.
Update
You can move nodes from the SVG subdocument to the main one using adoptNode
. With an empty <svg>
element (called target
) in the main document:
o = document.getElementById('thesvg').contentDocument.getElementById('theelement');
document.adoptNode(o);
document.getElementById('target').appendChild(o);
Again, not sure what the compatibility is for this, but it works in Safari. According to the W3C DOM FAQ, this is a DOM Level 3 method. Level 2 has importNode
which apparently allows a copy rather than a move. And as suggested by the same FAQ, you can always walk through the subdocument and re-create the hierarchy in the main document using createNode
and friends.
Upvotes: 2