How to dynamically change svg text content in html using javascript
My requirement is to remove the text element from g
and another text element. But when I run this code, the text that is written is removed fine, but adding a new text tag is not displayed. When I open the developer section in Chrome, it shows my added tag text
, but it doesn't appear in view. And when I update any thing from the chrome developer section, then the DOM reloads again and my new text is 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>
+3
source to share
3 answers
If you want to change the text, you don't need to delete the entire element and recreate it. You can simply change the textcontent by selecting the text element and set new content for it like this:
document.getElementById('t').childNodes[1].childNodes[1].innerHTML= "This is a paragraph";
See a 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>
+2
source to share