I add the following code (I try to add an element to svg) but it does not work, explain how to fix

$("#vmap svg path").prepend('<defs><pattern id="img1" patternUnits="userSpaceOnUse" width="600" height="450"><image xlink:href="daisy-grass-repeating-background.jpg" x="0" y="0" width="600" height="450" /></pattern></defs>') $("#vmap svg path").each(function(i,e){ $(e).attr("fill","url(#img1)") }) <div id="vmap"> <svg> <path d="M5,50 l0,100 l100,0 l0,-100 l-100,0 M215,100 a50,50 0 1 1 -100,0 50,50 0 1 1 100,0 M265,50 l50,100 l-100,0 l50,-100 z" fill="url(#img1)" /> </svg> </div> 

1 answer 1

jQuery, unfortunately, does not know how to create SVG elements . Therefore it is necessary in the old manner, through JS:

 //Элементы заливки var pattern = makeSVG('pattern', { id: 'img1', patternUnits:'userSpaceOnUse', width: '600', height: '450', x: '0', y: '0' }) var img1 = makeSVG('image', { 'href': 'https://placeimg.com/600/450/any', width: '600', height: '450', x: '0', y: '0' }) //добавляем defs, если его нет svg = $('#vmap svg')[0]; var defs = svg.querySelector('defs') || svg.insertBefore(makeSVG('defs'), svg.firstChild); defs.appendChild(pattern); pattern.appendChild(img1); //настраиваем стиль $("#vmap svg path").each(function(i, e) { $(e).attr("style", "fill:url(#img1)") }) //небольшая функция для упрощения жизни function makeSVG(tag, attrs) { var el = document.createElementNS('http://www.w3.org/2000/svg', tag); for (var k in attrs) el.setAttribute(k, attrs[k]); return el; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="vmap"> <svg> <path d="M5,50 l0,100 l100,0 l0,-100 l-100,0 M215,100 a50,50 0 1 1 -100,0 50,50 0 1 1 100,0 M265,50 l50,100 l-100,0 l50,-100 z" style="fill:url(#img1)" /> </svg> </div>