Search code examples
javascriptsvgprototypejs

Adding SVG element to HTML element with appendChild - failing in IE9?


I'm loading up an SVG file via a Prototype Ajax Request, adding a class and an id to it, then putting it into a div. My issue comes when adding it to the DOM:

onSuccess: function(response) { 

    var svgElement = response.responseXML.documentElement;
    svgElement.setAttribute("id", "someId");
    svgElement.setAttribute("class", "someClass");

    // At this point, everything is fine. I can verify that in IE9,
    // I have a valid svgElement and the id and class have been correctly set.

    var someDiv = $('someDiv');

    someDiv.appendChild(svgElement); // This fails in IE9, but works elsewhere!
    someDiv.insert(svgElement.xml); // This works in IE9, but fails elsewhere!

}

I'm only concerned with the better browsers of the bunch - IE9 is the lowest I have to worry about here.

Any ides what's up? I'm temporarily switching insert methods depending on if I'm in IE or not, but I want to get to the bottom of this and fix it the correct way.


Solution

  • I got around the "responseXML being in a different document" issue by simply creating my document new in all cases by using the responseText:

    onSuccess: function(response) { 
    
        var svgDoc;
    
        if (window.DOMParser) {
          var domParser = new DOMParser();
          svgDoc = domParser.parseFromString(response.responseText, "text/xml");
        } else {
          svgDoc = new ActiveXObject("Microsoft.XMLDOM");
          svgDoc.async = false;
          svgDoc.loadXML(response.responseText);
        }
    
        var svgElement = svgDoc.documentElement;
    
    }
    

    Way easier and cleaner than importing the document (and all associated issues) if you ask me.