03t02 03t02 - 3 months ago 94
Javascript Question

insert svg string element into an existing svg tag

I have an existing

<svg></svg>
, and I would like to append an
svg
element, which is a string.
Example:

var svg_string = '<g><text x="100" y="100">Hello</text></g>';

d3.select('svg').append(svg_string); // or something like that


Can I do that ? Without using
d3.xml
, because I don't want to load a svg file from somewhere.

And I've tried with jQuery by doing this.

$('svg').append('<svg><g><text></text></g></svg>')


But I would like to know if there is a better way, without appending svg tag

UPDATE: Sorry, I didn't make myself clear.

I would like to append the
svg_string
into a svg element like

<svg><g id="test"></g></svg>

$('#test').append(svg_string)


Thanks.

Answer

The correct practice is to declare each attribute or node explicitly.

d3.select('svg').append("g").append("text").attr("x",100).attr("y",100).text("Hello");

If you really want to add html string then use :

d3.select('svg').html("<g><text x=\"100\" y=\"100\">Hello</text></g>");

Example : https://jsfiddle.net/ero38b49/

EDIT : Based on question update :

If you wish to add string str inside <g> with id "test"

  var str = "<g><text x=\"100\" y=\"100\">Hello</text></g>";
    d3.select('#test').html(str);

This would give you :

<svg>
   <g id="test">
      <g><text y="100" x="100">Hello</text>
      </g>
   </g>
</svg>

Example : https://jsfiddle.net/ero38b49/1/

If you wish to append string str to<svg> ( as a sibling of <g> with id "test" )

d3.select("svg").html(d3.select("svg").html() + str);

This would give you :

<svg>
  <g id="test"/>
  <g><text y="100" x="100">Hello</text>
  </g>
</svg>

Example : https://jsfiddle.net/ero38b49/2/