13

I want to add items in an SVG via jQuery. I can well insert tags such as <rect /> or <text /> but I can not insert images with the tag <image />.

This tag becomes <img /> automatically, which can not display an image in SVG: http://jsfiddle.net/G4mJf/

How can I prevent this? If it is impossible, is there another way to insert images in SVG using JavaScript/jQuery.

pacien
  • 133
  • 1
  • 5
  • 1
    Try to use my jQuery hack [http://stackoverflow.com/questions/11792754/create-and-access-svg-tag-with-jquery/14985470#14985470][1] [1]: http://stackoverflow.com/questions/11792754/create-and-access-svg-tag-with-jquery/14985470#14985470 – Ruben Kazumov Feb 20 '13 at 21:29

2 Answers2

19

you should use createElementNS():

var img = document.createElementNS('http://www.w3.org/2000/svg','image');
img.setAttributeNS(null,'height','536');
img.setAttributeNS(null,'width','536');
img.setAttributeNS('http://www.w3.org/1999/xlink','href','https://upload.wikimedia.org/wikipedia/commons/2/22/SVG_Simple_Logo.svg');
img.setAttributeNS(null,'x','10');
img.setAttributeNS(null,'y','10');
img.setAttributeNS(null, 'visibility', 'visible');
$('svg').append(img);
Ram
  • 143,282
  • 16
  • 168
  • 197
2

jQuery alone cannot handle SVG manipulation properly, as this answer explains. You should probably be using Raphael, or one of the hacky methods described in the link above.

Community
  • 1
  • 1
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134