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.
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.