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

I wrote javascript that dynamically edits the svg element. I want to get a new line of an edited svg element, but currently my code is not working. I found the following code here to get a lowercase form of an HTML document.

var txt = document.documentElement.innerHTML; 

I just want the innerHTML an SVG element. I tried the following code but got the error "undefined".

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

How to do it. The error occurs in Google Chrome, but I want the solution to work in any browser.

+4
source share
2 answers

innerHTML defined for HTML documents, but not for XML DOMs of other types.

There is a specific mechanism for innerHTML like objects for SVG. http://www.w3.org/Graphics/SVG/WG/wiki/SVG_2_DOM#innerHTML_type_facilities :

innerHTML type objects

It would be nice if XML had an innerHTML function. Writing markup in an ECMAScript line can be a little painful, but it can also simplify a lot, and to be better, this is for script types in which it is useful, probably means features like E4X.

Calling this innerHTML would make it look like the markup should be parsed as being in the XHTML namespace, so it’s possible that innerMarkup or insertCode would be a better name, or for symmetry with textContent perhaps markupContent .

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

or see fooobar.com/questions/469901 / ... for the IE equivalent.

+10
source

Some actual codes (tested on 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> 
+1
source

Source: https://habr.com/ru/post/1394639/


All Articles