Reputation: 881
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.
Upvotes: 4
Views: 5796
Reputation: 82396
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>
Upvotes: 1
Reputation: 120586
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 maybeinnerMarkup
orinsertCode
would be a better name, or, for symmetry withtextContent
, maybemarkupContent
.
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.
Upvotes: 10