Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append SVGs to a <div>?

Though there are many answers on SO on how to append an SVG in a div but i couldn't get any of them to work for me. May be because i've never worked with SVGs before.

So, i'm creating an SVG on my node server and then creating a JSON object with some other data along with SVG in it

svgFiles.push({
   'file': svgDump, //This holds well created SVG
   'vp': JSON.stringify(viewport),
   'page': pageNum
});

and then sending it back as a response to my angularjs code.

$http({ ... }).then(function callback(resp) { // request to node server
  var svg = resp.data.file;
  var container = document.createElement('div');
  var oldContent = container.innerHTML; // There is going to be an array of objects with SVG data hence i need the 'APPEND' functionality
  // But currently assuming there is only 1 object for demo purpose
  container.innerHTML = oldContent + svg;
})

Now that i've my SVGs saved in a variable, i expected that appending it in any DIV should work.

Though it did work but it was all plain text including stuff like @font-face, src etc.

I'm sure there is something that i'm missing or not doing the right way. How can i achieve this?

like image 385
Tushar Shukla Avatar asked Oct 23 '25 02:10

Tushar Shukla


1 Answers

Finally found a solution for this with help of a friend.

All i needed to do was:

$http({ ... }).then(function callback(resp) { // request to node server
  var svg = resp.data.file;
  var container = document.createElement('div');
  var parser = new DOMParser();
  var doc = parser.parseFromString(svg, "image/svg+xml");
  container.appendChild(doc.documentElement);
});
like image 92
Tushar Shukla Avatar answered Oct 24 '25 15:10

Tushar Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!