Sayan
Sayan

Reputation: 2054

Adding elements to SVG on the fly, elements added to the HTML DOM but not rendered

I have a SVG which contains text within a rectangle. I would like to change the text at some user interaction.

Most of the code I have come across does something like this: (sample code is for adding a circle)

var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r",  20);
shape.setAttribute("fill", "green");

While I used:

function writeSVG() {
        clearSVG();
        var name = document.getElementById('txtName').value;
        var txtNode = '<text id="newTxt" x="300" y="300">' + name + '</text>';
        $('#svgElem').append(txtNode);
        $('#popUp').hide();
    }

//Removes all text from SVG rectangle
    function clearSVG() {
        $('#controls text').remove();
    }

and my SVG is written directly into the HTML

 <div id="controls">
        <svg id="svgElem" height="600" xmlns="http://www.w3.org/2000/svg" version="1.1">    Sorry, your browser does not support SVG.
        <rect id="rectSVG" width="500" height="500" style="fill:#FFFFFF;stroke:black;stroke-width:2;" onclick="launchPopUp();" />
       <text id="defaultTxt" x="200" y="200">Click in here!</text>
       </svg>
    </div>

NOTE: I am using Safari 5.1

Upvotes: 1

Views: 1619

Answers (1)

Alohci
Alohci

Reputation: 82986

The way you are creating the <text> element puts it in to the wrong namespace. Creating a string and then parsing it via .append() will put the element into the HTML namespace, not the SVG one.

You must wrap your string in <svg> and </svg> before parsing, and then append the children of the resultant root node to your <svg> element in the DOM.

Upvotes: 2

Related Questions