2

If I create any draw in SVG, and, instead of putting the code in HTML file, I insert from a JS file (with document.createElement('svg')), the svg and all its strokes are rendered with 0x0 size.

class Spinner {

  constructor(target) {

    this.target = document.getElementById(target);

    const spinner = document.createElement('svg');
    spinner.setAttribute('width', '100');
    spinner.setAttribute('height', '100');

    const spinnerPath = document.createElement('circle');
    spinnerPath.setAttribute('fill', 'red');
    spinnerPath.setAttribute('stroke', 'black');
    spinnerPath.setAttribute('stroke-width', '3');
    spinnerPath.setAttribute('cx', '50');
    spinnerPath.setAttribute('cy', '50');
    spinnerPath.setAttribute('r', '40');

    spinner.append(spinnerPath);

    this.target.append(spinner);

  }

}

new Spinner('here');
<div id="here"></div>
Angel Luis
  • 487
  • 2
  • 5
  • 19
  • 3
    SVG elements must be created with createElementNS, createElement is for HTML elements only. – Robert Longson Jan 28 '19 at 11:39
  • Use `const spinner = document.createElementNS(SVG_NS, 'svg');` where `const SVG_NS = 'http://www.w3.org/2000/svg';` The same for circle – enxaneta Jan 28 '19 at 11:42
  • 1
    see this post [Appended childs through appendChild() don't show up](https://stackoverflow.com/questions/54400888/appended-childs-through-appendchild-dont-show-up/54401101#54401101) – Maheer Ali Jan 28 '19 at 11:42
  • thank you @RobertLongson, worked with `document.createElementNS( 'http://www.w3.org/2000/svg','svg');` in each svg element. – Angel Luis Jan 28 '19 at 11:43

1 Answers1

2

Use createElementNS instead of createElement for SVG elements.

const ns = 'http://www.w3.org/2000/svg';

class Spinner {
    constructor(target) {
        this.target = document.getElementById(target);

        const spinner = document.createElementNS(ns, 'svg');
        spinner.setAttribute('width', '100');
        spinner.setAttribute('height', '100');

        const spinnerPath = document.createElementNS(ns, 'circle');
        spinnerPath.setAttribute('fill', 'red');
        spinnerPath.setAttribute('stroke', 'black');
        spinnerPath.setAttribute('stroke-width', '3');
        spinnerPath.setAttribute('cx', '50');
        spinnerPath.setAttribute('cy', '50');
        spinnerPath.setAttribute('r', '40');

        spinner.appendChild(spinnerPath);

        this.target.appendChild(spinner);
    }
}

new Spinner('here');
<div id="here"></div>
James Coyle
  • 9,922
  • 1
  • 40
  • 48