1

All:

What I want to do is:

<div id="container">
    <div class="unwanted"></div>
    <div class="unwanted"></div>
    <svg><rect></rect></svg>
    <div class="unwanted"></div>
<div>

How can I get the innerHTML of #container for that svg, so what I get is:

"<svg><rect></rect></svg>"
Kuan
  • 11,149
  • 23
  • 93
  • 201

3 Answers3

1

What you want is the outerHTML of the svg Element but that is not really accessible in this way. Here

outerHTML of an SVG element

is an idea of how to get the svg with content.

Community
  • 1
  • 1
Hauke S
  • 555
  • 5
  • 10
1

This will get you what you want in this case:

document.getElementById('container').getElementsByTagName('svg')[0].innerHTML;
Pavlin
  • 5,390
  • 6
  • 38
  • 51
0

jquery

var container = $("#container").html().find('svg');
// or
 $("#container svg").html();

//return <rect></rect> you can use '<svg>'+container+'</svg>'

javascript

var container = document.getElementById('container');
var svg = container.getElementsByTagName('svg')[0].innerHTML;

//return <rect></rect> you can use '<svg>'+container+'</svg>'

or see @Duopixel's answer on Why .html() doesn't work with SVG selectors using jquery ?

var svg = document.getElementById('svg_root'); // or whatever you call it
var serializer = new XMLSerializer();
var str = serializer.serializeToString(svg);
Community
  • 1
  • 1
Egy Success
  • 112
  • 1
  • 1
  • 8