Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

svg

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>
like image 468
Pranjal Avatar asked Nov 17 '25 08:11

Pranjal


1 Answers

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>
like image 99
jhinzmann Avatar answered Nov 19 '25 22:11

jhinzmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!