I'm trying to create a SVG element in JS then append it to the DOM. The SVG element references a symbol though. I can achieve this using the insertAdjacentHTML
method but not through appendChild
method.
When using appendChild
, all the right stuff is on the DOM according to browser inspectors but it's not rendered correctly. Can anyone see why?
http://codepen.io/bradjohnwoods/pen/dGpqMb?editors=101
<svg display="none">
<symbol id="symbol--circle--ripple" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="25" />
</symbol>
</svg>
<button id="btn">
</button>
<script>
var btn = document.getElementById('btn');
//var myString = '<svg><use xlink:href="#symbol--circle--ripple" width="100" height="100" class="btn--ripple__circle"></use></svg>';
//btn.insertAdjacentHTML('afterbegin', myString);
var svg = document.createElement('svg');
var use = document.createElement('use');
use.setAttribute("xlink:href", "#symbol--circle--ripple");
use.setAttribute("width", "100");
use.setAttribute("height", "100");
use.classList.add("btn--ripple__circle");
svg.appendChild(use);
btn.appendChild(svg);
</script>
<symbol> The <symbol> element is used to define graphical template objects which can be instantiated by a <use> element. The use of <symbol> elements for graphics that are used multiple times in the same document adds structure and semantics.
Changing Attribute Values Once you have obtained a reference to the SVG element you can change its attributes using the setAttribute() function. Here is an example: var svgElement = document. getElementById("rect1"); svgElement.
Since SVG images can be inlined in HTML, we can manipulate them with JavaScript. This means that we can animate parts of an image from code, make it interactive, or turn things around and generate graphics from data.
The “@” symbol is for tagging actual accounts within the social media platform. The “#” allows users to participate in a larger conversation with the rest of the Internet. The “@” lets you connect with a specific person.
You cannot create SVG elements using createElement
, you must use createElementNS
to create them in the SVG namespace
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
insertAdjacentHTML
invokes the html parser which magically fixes the element namespaces.
Similarly you can't use setAttribute to create attributes in the xlink namespace such as xlink:href. You want
setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#symbol--circle--ripple");
there
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