1

I am trying to insert text inside SVG using appendChild() method. I need to use this method for the actual code I am writing.

In the attached code, you will find that I am trying to write the string "How are you?" inside the SVG using appendChild() method. However it doesn't display. I checked the execution using Chrome developer tools, myTextElement and myText are actually executed in the code. I don't see why it is not being displayed, though. Can you please help?

var mysvg = document.getElementById("mysvg")
var myTextElement = document.createElement("text");
var myText = document.createTextNode("How are you?")

myTextElement.appendChild(myText);
mysvg.appendChild(myTextElement);
circle {
  fill-opacity: 0.5;
  stroke-width: 4;
  fill: #3080d0;
  stroke: #3080d0;
  opacity: 0.6;
}
<svg id="mysvg" version="1.1" xmlns="http://www.w3.org/2000/svg" width="400" height="300">
  <circle id="my-circle" cx="100" cy="100" r="50" />
  <text x="0" y="10" font-family="Verdana" font-size="55" fill="blue"> Hello </text>
</svg>
Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90

2 Answers2

3

Improved positioning of text for demo.

var mysvg = document.getElementById("mysvg");

var myTextElement = document.createElementNS("http://www.w3.org/2000/svg", "text");
var myText = document.createTextNode("How are you?");
myTextElement.setAttribute("x", "0");
myTextElement.setAttribute("y", "110");
myTextElement.setAttribute("fill", "blue");
myTextElement.setAttribute("font-family", "Verdana");
myTextElement.setAttribute("font-size", "55");

myTextElement.appendChild(myText);
mysvg.appendChild(myTextElement);
circle {
  fill-opacity: 0.5;
  stroke-width: 4;
  fill: #3080d0;
  stroke: #3080d0;
  opacity: 0.6;
}
<svg id="mysvg" version="1.1" xmlns="http://www.w3.org/2000/svg" width="400" height="300">
  <circle id="my-circle" cx="100" cy="100" r="50" />
  <text x="0" y="55" font-family="Verdana" font-size="55" fill="blue"> Hello </text>
</svg>
Vadim Ovchinnikov
  • 13,327
  • 5
  • 62
  • 90
0

It looks to me like <text> elements inside <svg>'s need the x and y property to display the text (otherwise they will default to 0). You can set the attributes of your text element in your <script>:

myTextElement.setAttribute('x', '20');
myTextElement.setAttribute('y', '20');

I'm sure these values will not be what you want, but they should allow you to see your inserted element.

One further source of error to remove - I would add your <script> tag just before the end of your <body> element, not inside your <svg>. I'm not certain, but with your script element where it is, the DOM element corresponding to your <svg> may not be defined at the time your script runs.

arbuthnott
  • 3,819
  • 2
  • 8
  • 21