Pranjal
Pranjal

Reputation: 463

How to dynamically change the text content of svg in html with javascript

My requirement is to remove the text element from g and another text element. But when I run this code, text which written is removed perfectly but adding new text tag is not showing. When I open the developer section of Chrome, it shows my added text tag but it is not showing in view. And when I update any thing from developer section of chrome then DOM again reload and my new text would be shown in view.

<!DOCTYPE html>  

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>
        <text x="10" y="10">hello</text>
    </g>
    </svg>
    <script>
            var s = document.getElementById('t');
            var g = s.childNodes[1];
            console.log(g.childNodes[1].remove());//remove text must in my case
            var txt = document.createElement('text');
            txt.setAttribute('x', '10');
            txt.setAttribute('y', '10');
            var t = document.createTextNode("This is a paragraph.");
            txt.appendChild(t);
            g.appendChild(txt);

    </script>        
    </body>
</html>

Upvotes: 3

Views: 6924

Answers (3)

Russell Pekala
Russell Pekala

Reputation: 109

If you're working within d3 you can simply do d3.select('#svgTextId').html(newHTML).

Upvotes: 0

jhinzmann
jhinzmann

Reputation: 988

If you want to change the text you don't have to remove the entire element and recreate it. You could simply change the textcontent by selecting the text element and set new content to it like following:

document.getElementById('t').childNodes[1].childNodes[1].innerHTML= "This is a paragraph";

See working example here:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <svg id="t">
    <g>
        <text x="10" y="10">hello</text>
    </g>
    </svg>
    <script>
            document.getElementById('t').childNodes[1].childNodes[1].innerHTML= "This is a paragraph";//remove text must in my case

    </script>        
    </body>
</html>

Upvotes: 3

adeneo
adeneo

Reputation: 318192

You have to use createElementNS when creating SVG elements

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

FIDDLE

Upvotes: 1

Related Questions