-1

I have an SVG image on the HTML page. The image is loaded fine and is visible on the screen. I try to access it with js, but no luck. The mimimal example:

<!DOCTYPE html>
<html lang="en">
    <body>
        <button onclick="print();">Print</button>
        <object data="drawing.svg" type="image/svg+xml" onload="print();"></object>
    </body>

    <script>
        function print() {
            var obj = document.body.getElementsByTagName("object")[0];
            console.log("obj = " + obj);
            console.log("obj.getSVGDocument() = " + obj.getSVGDocument());
            console.log("obj.contentDocument = " + obj.contentDocument);
            console.log("obj.firstElementChild = " + obj.firstElementChild);
            console.log("obj.childNodes.length = " + obj.childNodes.length);
        }
    </script>
</html>

Try to access it right after it was loaded or later on a button click, the console output is always:

obj = [object HTMLObjectElement]
obj.getSVGDocument() = null
obj.contentDocument = null
obj.firstElementChild = null
obj.childNodes.length = 0

I also checked the famous snippet, but it gave me

Uncaught TypeError: Cannot read property 'getElementById' of null at HTMLObjectElement.<anonymous>

Tested in Chrome and Mozilla Firefox. Am I missing something? The SVG is seen in the DOM with all its contents and elements. Why are they inaccessible then?

enter image description here

HoRn
  • 1,458
  • 5
  • 20
  • 25

1 Answers1

0

I solved the problem by placing the files on the Internet (previously they were offline).

After putting them online, I could reach contentDocument, it was no longer null. Console output:

obj.contentDocument = [object XMLDocument]

Then I could alter the contents of SVG with javascript...

HoRn
  • 1,458
  • 5
  • 20
  • 25