javascriptsvggetelementbyidobject-tag

document.getElementById results in null where moving svg into object tag


I'm trying to make my html document a more pleasant reading experience by moving the SVG file it uses into an object tag.

Part of the purpose of the SVG is to make it clickable - which in turn changes its colour. This is done via JavaScript.

Things works fine as long as the SVG is within the parent html but as soon as I try to use the object tag JavaScript getElementById fails (console.log(svg_rectangle) returns null). I'm assuming the DOM is no longer aware of the SVG element once moved into an Object tag so it's something to do with the scope?

Not much luck Googling this one, I'm no expert with the DOM so maybe I'm not using the right keywords.

I'm running this via Django hence the {{ STATIC_URL }}.

HTML

<html>
<body>

<object id="svg1" data="{{ STATIC_URL }}svg/test.svg" type="image/svg+xml"></object>

<!--
<svg
id="svg_square"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 height="256"
 width="256"
 version="1.1"
 xmlns:cc="http://creativecommons.org/ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">

<g class="region">
    <rect id="rect_front" transform="scale(1,-1)" height="64" width="64" y="-128" x="64" onclick="parent.testFunction(this.id)"/>
</g>
</svg>
-->

<script src="{{ STATIC_URL }}archive_140520/handle_svg.js" type="text/javascript"></script>

</body>
</html>

JavaScript

function testFunction(id){
    console.log(id)
    var svg_rectangle = document.getElementById(id);
    console.log(svg_rectangle)
    svg_rectangle.style.fill="green"
}

SVG (test.svg)

<svg
id="svg_square"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns="http://www.w3.org/2000/svg"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 height="256"
 width="256"
 version="1.1"
 xmlns:cc="http://creativecommons.org/ns#"
 xmlns:dc="http://purl.org/dc/elements/1.1/">

<g class="region">
    <rect id="rect_front" transform="scale(1,-1)" height="64" width="64" y="-128" x="64"        onclick="parent.testFunction(this.id)"/>
</g>
</svg>

Solution

  • you need to address the contentDocument of object to get its inner elements, try something like:

    var svg_rectangle = document.getElementById("svg1").contentDocument.getElementById("svg_square");