Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting text SVG element dynamically via javascript

Tags:

javascript

svg

I am creating SVG elements via JavaScript, and it works fine, but when I create an text SVG element and define it's content, the browser just don't render the value, despite the value is in the code when I inspect it with firebug.

The code is:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('xlink','http://www.w3.org/1999/xlink'); svg.setAttribute('width','187'); svg.setAttribute('height','234');  var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.setAttribute('width','187'); rect.setAttribute('height','234'); rect.setAttribute('fill','#fff'); rect.setAttribute('stroke','#000'); rect.setAttribute('stroke-width','2'); rect.setAttribute('rx','7');  var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text'); text.setAttribute('x', '10'); text.setAttribute('y', '20'); text.setAttribute('fill', '#000'); text.textContent = '2';  svg.appendChild(rect); svg.appendChild(text);   var wp = document.getElementById('wrapper');  wp.appendChild(svg); 

Here is the jsfiddle link. If you inspect the SVG you will see the value of the text element there, but the browser doesn't render it.

Thanks

like image 320
and-k Avatar asked Feb 07 '13 18:02

and-k


People also ask

Can SVG integrate with JavaScript?

Details about each SVG attribute. Details about the SVG DOM API, for interaction with JavaScript. SVG works together with HTML, CSS and JavaScript.

Does Z Index work with SVG?

Contrary to the rules in CSS 2.1, the z-index property applies to all SVG elements regardless of the value of the position property, with one exception: as for boxes in CSS 2.1, outer 'svg' elements must be positioned for z-index to apply to them.


2 Answers

You're short an "h" in your namespace

Was

var text = document.createElementNS('ttp://www.w3.org/2000/svg', 'text'); 

should be

var text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); 
like image 155
cmonkey Avatar answered Sep 19 '22 22:09

cmonkey


    function createText() {    var newText = document.createElementNS(svgNS,"text");   newText.setAttributeNS(null,"x",20);         newText.setAttributeNS(null,"y",100);      var textNode = document.createTextNode("milind morey");   newText.appendChild(textNode);   document.getElementById("firstGroup").appendChild(newText); } 

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300">            <g id="firstGroup">      <text x="20" y="45" onclick="createText();" font-size=+13px">Click on this text to create a new text.</text>    </g>        </svg> 
like image 41
Milind Morey Avatar answered Sep 18 '22 22:09

Milind Morey