Johan Johan - 2 years ago 70
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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download