Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the string of a dynamically modified SVG element of an HTML document?

Tags:

javascript

svg

I wrote javascript which dynamically edits an svg element. I want to get the new string of the edited svg element but currently my code fails. I found here the following code to get the string form of an HTML document.

var txt = document.documentElement.innerHTML;

I just want the innerHTML of the SVG element. I tried the following code but get an error message saying "undefined".

var svgnode=document.getElementById("svgnode1");
alert(svgnode.innerHTML);

How do I do that. The error occurs on Google Chrome but I want a solution that works on any browser.

like image 524
seven_swodniw Avatar asked Dec 22 '22 02:12

seven_swodniw


2 Answers

innerHTML is defined for HTML documents but not for XML DOMs of other kinds.

There is some mechanism planned for innerHTML like facilities for SVG. http://www.w3.org/Graphics/SVG/WG/wiki/SVG_2_DOM#innerHTML_type_facilities:

innerHTML type facilities

It would be good if XML had an innerHTML-like feature. Writing markup in an ECMAScript string can be a bit of a pain, but it can also simplify things a lot, and to get better that that for the types of scenario in which it's useful probably means E4X-like capabilities.

Calling this facility innerHTML would make it seem like the markup should be parsed as being in the XHTML namespace, so maybe innerMarkup or insertCode would be a better name, or, for symmetry with textContent, maybe markupContent.

If what you need is a way to turn SVG, or any other XML DOM into a string of XML, see https://developer.mozilla.org/en/Parsing_and_serializing_XML

  • XMLSerializer to serialize DOM trees to strings

or see https://stackoverflow.com/a/4916895/20394 for the IE equivalent.

like image 125
Mike Samuel Avatar answered Dec 23 '22 16:12

Mike Samuel


Some actual code (Tested in Google-Chrome and IE 11):

<object id="sv" data="Switzerland_regions.svg" type="image/svg+xml">
    <!-- <img src="yourfallback.jpg" />-->
</object>


<script type="text/javascript">
        var S = document.getElementById("svgnode1")

        var markup = (new XMLSerializer()).serializeToString(S.contentDocument.rootElement);
        console.log(markup);


        // var SD = S.getSVGDocument();

        // var circle1 = SD.getElementById("GR");
        // console.log(circle1);
        // circle1.style.fill = "grey";

         //var rectangle = SD.querySelector("#layer4");
        //var parent = rectangle.parentNode;
        //parent.removeChild(rectangle);
</script>
like image 38
Stefan Steiger Avatar answered Dec 23 '22 16:12

Stefan Steiger