Search code examples
javascriptsvgimportincludeexternal

Acess and manipulate groups of an svg that is inside of an object tag


For exemple, i have this code that i know how to manipulate:

<g id="box">
   <path class="st4" d="M893,577H359c-6.6,0-12-5.4-12-12V323c0-6.6,5.4-12,12-12h534c6.6,0,12,5.4,12,12v242
       C905,571.6,899.6,577,893,577z"/>
</g>
</svg>


<!--External calls-->
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>


</html>

i can manipulate the group "box" with this java script object:

const svg = document.getElementById("box");

but what if i do that:

<html>
    <object data="my_svg.svg"></object>


<!--External calls-->
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>


</html>

How can i acess the box group that is inside this svg in this object tag?


Solution

  • As long as the SVG is of the same origin as your page, you can access it through the object's contentDocument.

    <html>
        <object data="my_svg.svg" id="box"></object>
    </html>
    
    document.getElementById("box").contentDocument.children[0] // should be the svg element