Brad Woods
Brad Woods

Reputation: 1546

SVG scripting with <symbol>

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>

Upvotes: 8

Views: 2020

Answers (2)

Robert Longson
Robert Longson

Reputation: 124289

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

Upvotes: 6

Brad Woods
Brad Woods

Reputation: 1546

I found the solution, .createElementNS & .setAttributeNS had to be used.

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#symbol--circle--ripple');

Upvotes: 0

Related Questions