view raw
03t02 03t02 - 9 months ago 172
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>';'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>




The correct practice is to declare each attribute or node explicitly.'svg').append("g").append("text").attr("x",100).attr("y",100).text("Hello");

If you really want to add html string then use :'svg').html("<g><text x=\"100\" y=\"100\">Hello</text></g>");

Example :

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>";'#test').html(str);

This would give you :

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

Example :

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

This would give you :

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

Example :