简体   繁体   中英

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>

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> 

You have to use createElementNS when creating SVG elements

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

FIDDLE

如果你在d3中工作,你可以简单地做d3.select('#svgTextId').html(newHTML)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM