Royal Pinto
Royal Pinto

Reputation: 2911

Dynamically rendered SVG is not displaying

I have the following svg object which if I put in html page directly without using code(static) it renders properly.

but same svg content if I insert into my html page using JavaScript it is not showing and if I open it in firebug and inspect svg and try to edit svg tag, it displays.

What could be the problem

<svg height="100" width="100">
  <rect width="100" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"></rect>
</svg>

I am adding svg dynamically using below code, here container will be my div which is there under body

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

        viewPort.setAttribute('height', 100);

        viewPort.setAttribute('width', 100);

        container.innerHTML = '';

        container.appendChild(viewPort);

After this I am adding rect inside this using

            boardElement = document.createElement('rect');

            boardElement.setAttribute('width', '100');

            boardElement.setAttribute('height', '100');

            boardElement.setAttribute('y', '1');

            boardElement.setAttribute('x', '1');

            boardElement.setAttribute('style', "fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)");


viewPort.appendChild(boardElement);

Upvotes: 37

Views: 16978

Answers (2)

Denis TRUFFAUT
Denis TRUFFAUT

Reputation: 1205

I confirm that the NS should be set for every element

document.createElementNS('http://www.w3.org/2000/svg', 'svg') document.createElementNS('http://www.w3.org/2000/svg', 'path')

Upvotes: 2

Lkrups
Lkrups

Reputation: 1344

The element boardElement should be declared like so

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

Upvotes: 59

Related Questions