I am facing an issue with adding a text element to my existing svg using a mouseover event. The code seems to work fine in general, but I am having trouble appending the created text element to the existing svg file (root). I have tried various methods, including var root = doc.documentElement
and var root = doc.rootElement
, but none of them seem to work for me. Additionally, using svgNS or null while creating the elements does not make any difference.
Below is the code snippet:
<script type="text/ecmascript">
<![CDATA[function showText(evt) {
var doc = evt.target.ownerDocument;
var root = doc.documentElement;
var text = doc.createElementNS(null, "text");
text.setAttributeNS(null, "x", "10");
text.setAttributeNS(null, "y", "30");
text.setAttributeNS(null, "font-size", "12");
var textNode = doc.createTextNode("test");
text.appendChild(textNode);
root.appendChild(text);
}]]>
</script>
Complete code of my svg:
<?xml version="1.0" encoding="UTF-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" style="stroke:black" height="600" width="800">
<rect width="800" x="0" y="0" height="600" style="fill:none" />
<rect width="800" x="0" id="textbox" y="540" height="60" style="fill:none" />
<rect width="720" x="40" y="30" height="480" style="fill:none" />
<line y2="510" x1="40" x2="760" y1="510" />
<line y2="510" x1="40" x2="40" y1="30" />
<text font-size="12" x="40" y="530">Time (X)</text>
<text font-size="12" x="5" y="20">Data (Y)</text>
<polyline style="stroke:black;fill:none;" points="91.84,217.19189757859385 143.68,323.2917668597486 195.52,235.86502103932202 247.36,43.359991864346625 299.2,202.8 351.04,315.903272925833 402.88,160.41241257803188 454.72,157.66691947582518 506.56,387.2047460928005 558.4,183.60000000000002 610.24,260.73963745895736 662.08,59.445816214522495 713.9200000000001,283.88097314947527 "
stroke-width="2" />
<script type="text/ecmascript">
< ![CDATA[function showText(evt) {
var doc = evt.target.ownerDocument;
var root = doc.documentElement;
var text = doc.createElementNS(null, "text");
text.setAttributeNS(null, "x", "10");
text.setAttributeNS(null, "y", "30");
text.setAttributeNS(null, "font-size", "12");
var textNode = doc.createTextNode("test");
text.appendChild(textNode);
root.appendChild(text);
}]] >
</script>
<circle id="circle" text="This is a test" r="10" cx="400.0" onmouseover="showText(evt)" cy="510">This is a test</circle>
</svg>