问题
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