Add a child node to an inline SVG with JavaScript. Imposible on IE9?

狂风中的少年 提交于 2019-12-24 04:06:33

问题


I just want add a new text node in a SVG on a html using accion() javaScript function:

<!DOCTYPE> 
<html>
<body>
<head>
<script type="text/javascript"> 
    function accion(){
        var SVGDocument = document.getElementById("idSVG");
        var text2 = SVGDocument.createTextNode("text");
        SVGDocument.appendChild(text2);
}       
</script>
</head>

<input type="button" onclick="accion()" value="GO!!"/>

<svg id="idSVG">
   <text id="texto" x="50" y="35" font-size="14">PRUEBA</text>
</svg>

</body>
</html>

But SVGDocument.createTextNode("text"); return an error: Object does not support this property or method. I think the problem is I can't get a correct reference to idSVG element. I'm using IE9.


回答1:


The example below works for me.

Note that if you don't set a y co-ordinate the default 0, 0 is likely outside the svg bounding box.

<!DOCTYPE> 
<html>
<body>
<head>
<script type="text/javascript"> 
    function accion(){
        var svg = document.getElementById("idSVG");
        var text2 = document.createElementNS("http://www.w3.org/2000/svg", "text");
        text2.setAttribute("y", "100");
        var textContent = document.createTextNode("this is the text content");
        text2.appendChild(textContent);
        svg.appendChild(text2);
}       
</script>
</head>

<input type="button" onclick="accion()" value="GO!!"/>

<svg id="idSVG">
   <text id="texto" x="50" y="35" font-size="14">PRUEBA</text>
</svg>

</body>
</html>


来源:https://stackoverflow.com/questions/14749983/add-a-child-node-to-an-inline-svg-with-javascript-imposible-on-ie9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!