I have an svg file containing a group with a single line element. I can make use of the use
element and make several reference copies in any position I want them. However, I want to use javascript to add and remove the use
element dynamically. Is there a way to use javascript to insert an svg use
element of my line into my group?
<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="" xmlns:xlink="" x="0px"
y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333"
xml:space="preserve">
<g id="ledgerlines">
<line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/>
</g>
</svg>
I have an svg file containing a group with a single line element. I can make use of the use
element and make several reference copies in any position I want them. However, I want to use javascript to add and remove the use
element dynamically. Is there a way to use javascript to insert an svg use
element of my line into my group?
<svg version="1.1" id="ex1-3rds-quarter-s" xmlns="http://www.w3/2000/svg" xmlns:xlink="http://www.w3/1999/xlink" x="0px"
y="0px" width="323.333px" height="55.333px" viewBox="0 0 323.333 55.333" enable-background="new 0 0 323.333 55.333"
xml:space="preserve">
<g id="ledgerlines">
<line id="MidCLine1" fill="none" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" x1="48.09" y1="41.694" x2="57.924" y2="41.694"/>
</g>
</svg>
Share
Improve this question
edited Sep 21, 2018 at 15:13
divibisan
12.2k11 gold badges43 silver badges62 bronze badges
asked May 5, 2014 at 0:12
Christopher GastonChristopher Gaston
5112 gold badges7 silver badges19 bronze badges
1 Answer
Reset to default 21var svgns = "http://www.w3/2000/svg";
var xlinkns = "http://www.w3/1999/xlink";
// Get a reference to the <g> element
var g = document.getElementById("ledgerlines");
// Create a <use> element
var use = document.createElementNS(svgns, "use");
// Add an 'href' attribute (using the "xlink" namespace)
use.setAttributeNS(xlinkns, "href", "#MidCLine1");
// Offset the line down by 10
use.setAttribute("y", "10"); // offset = y+10
// Add the <use> to the <g>
g.appendChild(use);
Demo here