Work with elements from embed or object tag

2019-01-18 06:42发布

问题:

I have an svg graphics inserted in the page with an embed or object tag:

<object data="graphics.svg" type="image/svg+xml" id="graphics" />

The image is loading properly and I can see its SVG structure with the browser debugger. I see all the elements ids and attributes but it seems to me there is no way to select those elements with my scripts on page:

$('#graphics path').length; // 0 (jQuery)
$('path').length; // 0 anyway

Is it possible to browse the graphics elements as usual?

回答1:

It will show up as a separate document, similar to an iframe. You can access it like this:

var svg = document.getElementById('graphics').contentDocument

Note that it is important to wait until the svg file is loaded; you might want to put your code in the object element’s onload event handler, like this:

<object data="graphics.svg" type="image/svg+xml" id="graphics" />
<script>
  document.getElementById('graphics').addEventListener('load',function(){
    var svg = document.getElementById('graphics').contentDocument
    // do stuff, call functions, etc.
  })
</script>