Can't access SVG by its ID

2019-08-05 09:28发布

问题:

I want to access the id of the svg and its paths after the file has loaded for interactive use. I load the SVG with a function and import the node to the DOM. Neither in document.ready nor in document.addEventListener("DOMContentLoaded", function(event) i am able to get the element by its id. The only way to get it is to set a timeout around the interactive code.

What i want is that the SVG (900kb) und its DOM should load before all other code is loaded. But until now i couldn find a fiting solution.

I am very confused because if i look at the DOM in the browser with firebug i am able to see the div with the ID but i cant get it .... And i cant find a issue in my code because i load it in the DOM and access it after DOM is ready ? Anyone here who find a solution?

This is my code to load the svg:

function fetchXML  (url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function (evt) {

        if (xhr.readyState === 4) {
            callback(xhr.responseXML);          
        }

        };
        xhr.send(null);
    };

    fetchXML("svg/bez_grey.svg",function(newSVGDoc){
        var n = document.importNode(newSVGDoc.documentElement,true);
        var mysvg = document.getElementById("map"); 

        mysvg.appendChild(n);

    })  

document.addEventListener("DOMContentLoaded", function(event) {

// Access the SVG-Elements here 

}):

回答1:

You need to call document.documentElement.appendChild(n); before calling var mysvg = document.getElementById("map");. This loads n into document's DOM. You can delete statement mysvg.appendChild(n);

This solution is based on working code example here: https://stackoverflow.com/a/3378320