How can I add <use> to the embedded SVG using jQuery (or, if necessary, simple JavaScript)?

I have a built-in SVG with an HTML5 document and would like to add using jQuery (or, if necessary, simple JavaScript).

I know how to add a rectangle, circle, or other shape, but I still can’t reuse the existing one.

Here is the jsFiddle test: http://jsfiddle.net/nhoizey/uDVbn/

SVG:

<svg width="300" height="300"> <symbol id="piece"><circle cx="50" cy="50" r="40" fill="green" /></symbol> <circle cx="70" cy="90" r="20" stroke="blue" fill="white" /> </svg> 

JavaScript:

 // it works! var rect = $(document.createElementNS("http://www.w3.org/2000/svg","rect")) .attr({ x: 10, y: 30, width: 50, height: 70, stroke: "red", fill: "white" }); $("svg").append(rect); // it doesn't work var newPiece = $(document.createElementNS("http://www.w3.org/2000/svg","use")) .attr({ "xlink:href": "#piece", transform: "translate(100, 100)" }); $("svg").append(newPiece); 

I know there is a jQuery SVG plugin, but would like to keep it as light as possible.

+4
source share
1 answer

The correct way to add the href attribute is to use setAttributeNS.

 useElement.setAttributeNS("http://www.w3.org/1999/xlink", 'href', '#piece'); 
+4
source

Source: https://habr.com/ru/post/1393336/


All Articles