Reputation: 117
I'm writing a snippet of code that creates a new SVG element but I'm having trouble setting the width and height properties.
var svg = document.createElement("svg");
while(!svg); // wait for it
svg.setAttribute("width", "100");
svg.setAttribute("height", "100");
document.body.appendChild(svg);
Upon inspection, the element has the two properties correctly set, and the .getAttribute()
method returns the correct values, but it is displayed as svg 0 × 0
when I hover my cursor on it. I'm probably missing something very obvious but I can't seem to make out what it is. Any ideas?
Upvotes: 2
Views: 1818
Reputation: 3238
You can try this code
function svg(){
// create the svg element
const svg1 = document.createElementNS("http://www.w3.org/2000/svg", "svg");
// set width and height
svg1.setAttribute("width", "500");
svg1.setAttribute("height", "500");
// create a circle
const cir1 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
cir1.setAttribute("cx", "200");
cir1.setAttribute("cy", "200");
cir1.setAttribute("r", "200");
cir1.setAttribute("fill", "red");
// attach it to the container
svg1.appendChild(cir1);
// attach container to document
document.getElementById("svg54583").appendChild(svg1);
}
svg();
<div id="svg54583"></div>
Upvotes: 1