Uchenna Ajah
Uchenna Ajah

Reputation: 368

How to create a valid svg element with javascript

I was working with SVG and i created an svg element. I added a <rect> element directly into the svg with html and then I created a new element (without namespace) <circle> with javascript and appended it to the svg element. The <rect> element displayed in the svg viewbox but the <circle> element did not display.

I got the <rect> and <circle> on the console and checked the constructor. The <rect> element returned SVGRectElement but the <circle> returned HTMLUnknownElement. I created a new <circle> element (with namespace: https://www.w3.org/2000/svg) and checked the constructor which returned Element.

Whichever way, appending both the namespaced and non-namespaced <circle> element to the svg did not appear in the svg viewbox. So how do i create a recognized svg element with javascript that will return SVGCircleElement?.

   var circle = document.createElement('circle');
    circle.setAttribute('cx', '10');
    circle.setAttribute('cy', '10');  
    circle.setAttribute('r', '30');
    circle.setAttribute('fill', 'red');

    var circle_2 = document.createElementNS('https://www.w3.org/2000/svg','circle');
    circle.setAttribute('cx', '5');
    circle.setAttribute('cy', '20');  
    circle.setAttribute('r', '30');
    circle.setAttribute('fill', 'blue');

    var svg = document.getElementById('svgx');
    var rect = document.getElementById('svgrect');
    svg.appendChild(circle);
    svg.appendChild(circle_2);

    console.log(svg.constructor); // SVGSVGElement() { [native code] }
    console.log(rect.constructor); // HTMLRectElement() { [native code] }
    console.log(circle.constructor); // HTMLUnknownElement() { [native code] }
    console.log(circle_2.constructor); // Element() { [native code] }
<svg style='width: 100%;' id='svgx'>
<rect x='5' y='5' width='50' height='30' fill='black' id='svgrect'>
</svg>

Upvotes: 4

Views: 4718

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

Remove the "s" from "https".

var circle_2 = document.createElementNS('http://www.w3.org/2000/svg','circle');

Even though it looks like a URL. It is really just a string constant that indicates this XML file is an SVG file. The namespace constant has to be exactly as presented here.

Also you need to change circle to circle_2 for that section of code.

var circle_2 = document.createElementNS('http://www.w3.org/2000/svg','circle');
circle_2.setAttribute('cx', '5');
circle_2.setAttribute('cy', '20');  
circle_2.setAttribute('r', '30');
circle_2.setAttribute('fill', 'blue');

var svg = document.getElementById('svgx');
var rect = document.getElementById('svgrect');
svg.appendChild(circle_2);
<svg style='width: 100%;' id='svgx'>
<rect x='5' y='5' width='50' height='30' fill='black' id='svgrect'>
</svg>

Upvotes: 2

Related Questions