0

The manipulation of a tagged svg worket perfectly but the manipulation of a svg-file in the object-tag only workes on Firefox, IE and Edge. But not in Chrome and Opera. I'm sitting for hours on it because it is necessary for me to manipulate svg-files through all browsers. I hope anyone can help me out. The solutions on other topics shows up with the same incompatibility.

JavaScript and SVG in HTML

How to access SVG elements with Javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

</head>
<body>
    <object data="Vernetzung.svg" type="image/svg+xml" width="100%" id="vernetzung">Your browser doesn't support SVG</object>

    <svg id="svgObject" height="40px" width="40px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800">
        <rect id="svgItem" width="800" height="800" fill="red"></rect>
    </svg>

    <script>
        function rotate() {
            // rotate in html-svg
            var svgItem = document.getElementById("svgItem");
            svgItem.setAttribute('transform', 'rotate(20)');

            //rotate in svg-file
            var a = document.getElementById('vernetzung');
            var svgDoc = a.contentDocument;
            var P1 = svgDoc.getElementById("P1");
            P1.setAttribute('transform', 'rotate(20)');
        }

        window.onload = function () {
            rotate();
        }
    </script>
</body>
</html>

That is the example file "Vernetzung.svg":

<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">
<rect id="P1" width="800" height="800" fill="blue"></rect>
</svg>

Chrome throw an arrow on this line:

var P1 = svgDoc.getElementById("P1");

Chrome error message:

Uncaught TypeError: Cannot read property 'getElementById' of null
at rotate (svg_Test.html:21)
at window.onload (svg_Test.html:26)
rotate @ svg_Test.html:21
window.onload @ svg_Test.html:26
load (async)
(anonymous) @ svg_Test.html:25

If I set the function by onload the object:

<object onload="rotate()" data="Vernetzung.svg" type="image/svg+xml" width="100%"  id="vernetzung"></object>

It works only in Firefox, IE and Edge, too.

kei101
  • 1
  • 2
  • 1
    Can you also show the content of `Vernetzung.svg`? Also, do you have any error in the dev-tools console? As a blind shot I would say the window's onload event fires before the ``'s one, which would make the `svgDoc` null, but it's really hard to tell with the little you gave. – Kaiido Jul 10 '18 at 01:16
  • I added some details, thx for your readiness to help – kei101 Jul 10 '18 at 08:25
  • Interesting... From where do you load your html page? Is it from the `file://` protocol? If so, then try from a server (even localhost). Otherwise, do you have some css that would hide this ``? – Kaiido Jul 10 '18 at 08:28
  • yes it was by file://. Now, I have tried it on a server as you say and it works in all browsers, really thx!! I never thought that this would require a server – kei101 Jul 10 '18 at 09:00

0 Answers0