When loading the page, the image is not visible (image = document.createElementNS (" http://www.w3.org/2000/svg ", 'image');)) But If in the object inspector, in Google Devs, copy the html code of the image and paste - the picture is displayed

var svg = document.createElementNS("http://www.w3.org/2000/svg","svg"); var el = document.getElementById('container') el.appendChild(svg) var image = document.createElementNS("http://www.w3.org/2000/svg", 'image'); image.setAttribute('width' , '400px') image.setAttribute('height' , '400px') image.setAttribute('x' , '0') image.setAttribute('y' , '0') image.setAttribute('xlink:href' , 'http://picfun.ru/wp-content/uploads/HTxyUcwXfw.jpg') svg.appendChild(image) http://codepen.io/anon/pen/rLROpB?editors=1010 

2 answers 2

You need to wrap your code in DOMContentLoaded and use setAttributeNS instead of setAttribute.

 document.addEventListener("DOMContentLoaded", function(event) { var svg = document.createElementNS("http://www.w3.org/2000/svg","svg"); var el = document.getElementById('container'); el.appendChild(svg); var image = document.createElementNS("http://www.w3.org/2000/svg", 'image'); image.setAttributeNS(null,'width' , '463'); image.setAttributeNS(null,'height' , '412'); image.setAttributeNS(null,'x' , '0'); image.setAttributeNS(null,'y' , '0'); image.setAttributeNS('http://www.w3.org/1999/xlink','href', 'http://picfun.ru/wp-content/uploads/HTxyUcwXfw.jpg'); image.setAttributeNS(null, 'visibility', 'visible'); svg.appendChild(image); svg.setAttribute('width' , '400px'); svg.setAttribute('height' , '400px'); }); 

Here is a link to the working code https://jsfiddle.net/3k8wka88/

  • I request a link to such a working solution - Den Rash
  • Corrected the code and put the link. - Andrii Kulyk

All because of "SVG native attributes (not including xlink: href) the SVG namespace; you can use just setAttribute instead of setAttributeNS, or use"

It works here: https://stackoverflow.com/questions/6701705/programmatically-creating-an-svg-image-element-with-javascript