The DOM already includes an empty SVG tag (svg
). When I try to dynamically append a USE
tag of an existing SVG symbol (symbol
) with an id (iconId
):
svg.empty();
svg[0].setAttribute('viewBox', symbol.getAttribute('viewBox'));
svg.append('<use xlink:href="#' + iconId + '"></use>');
it no longer renders the SVG. In Chrome, it renders if I add:
element.html(element.html());
or manually manipulate the viewBox
attribute, but that's not a real solution and IE doesn't like it at all.
It's worth mentioning that if I append SVG graphics directly, the element renders.
What is happening here and why isn't the SVG drawing after appending the USE tag?
After all it was indeed a matter of namespaces.
Specifically, SVG elements and attributes must be created and set using document.createElementNS
and node.setAttributeNS
.
$(document).ready(function(evt) {
var svgns = 'http://www.w3.org/2000/svg',
xlinkns = 'http://www.w3.org/1999/xlink',
use = document.createElementNS(svgns, 'use');
use.setAttributeNS(xlinkns, 'xlink:href', '#save');
document.getElementById('useSVG').appendChild(use);
});
#svgStore {
display: none;
}
#useSVG {
width: 16px;
height: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<svg style="display:none;" id="svgStore" style="display: none;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<symbol viewBox="0 0 16 16" id="save"><title>save</title> <g id="svgstore3748a955346b4a088bbdc55a22f56504_x31_6_13_">
<path style="fill-rule:evenodd;clip-rule:evenodd;" d="M9,4h2V2H9V4z M13,13H3v1h10V13z M13,11H3v1h10V11z M13,0H0v16h16V3L13,0z
M3,1h9v4H3V1z M14,15H2V8h12V15z M13,9H3v1h10V9z">
</path>
</g>
</symbol>
</svg>
SVG use:
<svg id="useSVG" xmlns="http://www.w3.org/2000/svg"></svg>
Thanks to @RobertLongson and http://www.kevlindev.com/tutorials/basics/shapes/js_dom/ for directing to the answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With