03t02 03t02 - 1 year ago 391
Javascript Question

insert svg string element into an existing svg tag

I have an existing

, and I would like to append an
element, which is a string.

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
, because I don't want to load a svg file from somewhere.

And I've tried with jQuery by doing this.


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
into a svg element like

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



Answer Source

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


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>";

This would give you :

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

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 :

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download