Reputation: 5235
I would append a textnode to a g
svg element.
Nothing is being printed on screen when I trigger my function
But it workd when I append TextNode
element directly to body
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var t = document.createTextNode("Hello World");
document.body.appendChild(g);
g.appendChild(t)
}
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
This code works without using g
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var t = document.createTextNode("Hello World");
document.body.appendChild(t);
}
<p>Click the button to create a Text Node.</p>
<button onclick="myFunction()">Try it</button>
Upvotes: 1
Views: 104
Reputation: 33024
You need to create a text element as well and append everything to an svg element. In this case I use an svg element with a viewBox that allows me to see the text although I didn't set any values for the x and y attributes. Depending on your viewBox you may need to set those attributes too.
function myFunction() {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
text.textContent = "Hello World";
g.appendChild(text);
svg.appendChild(g);
}
<p>Click the button to create a Text Node.</p>
<svg id="svg" viewBox="-100 -50 200 100" width="200"></svg>
<button onclick="myFunction()">Try it</button>
Upvotes: 2