Johan Johan - 3 months ago 5
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");

var thisRect = svg.lastChild;

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


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?


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

document.createElementNS("", "svg");

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

svg.setAttributeNS("", "xmlns:xlink", "");

Demo click here