Johan Johan - 5 months ago 10
HTML Question

How should I properly use setAttribute() method?

I have a single svg element to which I'm adding a rect element with the createElement() method and then giving it its width and height with the setAttribute() method.

var svg = document.querySelector("svg");

function addRect(side) {
var newRect = document.createElement("rect");
svg.appendChild(newRect);

var thisRect = svg.lastChild;

thisRect.setAttribute("width", side);
thisRect.setAttribute("height", side);
}

addRect("100");


http://codepen.io/stromqvist/pen/YWZpNb

The result in chrome dev tools show
<rect width="100" height="100"></rect>
, yet the rect doesn't have any dimensions.

What am I doing wrong?

Answer

When creating SVG elements, you'd use createElementNS to create elements with a qualified namespace, like SVG elements

document.createElementNS("http://www.w3.org/2000/svg", "svg");

and for certain attributes you'd use setAttributeNS, but for regular attributes like width and height, setAttribute should work

svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");

Demo click here

Comments