Mar Cnu
Mar Cnu

Reputation: 1175

Acces SVG file included in HTML file

I included a SVG file in my HTML document with <embed src="mySvg.svg" /> and now I want to manipulate what is inside my SVG.

I found that the SVG is not in "document" but in "window".

In my SVG file, I have a script :
(the init function in launch onload)
function init(evt) {
svgDocument = evt.target.ownerDocument; svgDocument.getElementById('anIdOfMySvgFile'); // I successfully get the element of the SVG file
this.parent.document.getElementById('anIdOfMyHtmlFile'); // I successfully get the element of the HTML file
}

But how can I select an element from my SVG file with a script located in my HTML file ?
window.document is my HTML file ... but I don't know how my SVG file is identified !

Upvotes: 2

Views: 1181

Answers (1)

benesch
benesch

Reputation: 5269

Set an ID on the embed, then use document.getElementById to grab it. Make sure to access the SVG through getSVGDocument().

<embed src="mySvg.svg" id="mySvg" />

<script type="text/javascript">
        var mySvg = document.getElementById("mySvg");
        mySvg.addEventListener("load", function() {
            var svg = mySvg.getSVGDocument();
            svg.getElementById("[insert svg element id here]");
        }
</script>

Upvotes: 5

Related Questions