The operation failed to add the SVG element to the main SVG container

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>

Answer №1

To properly create SVG elements, they must be defined within the SVG namespace like so:

var newText = doc.createElementNS("http://www.w3.org/2000/svg", "text");

It's important to note that spaces in the CDATA section markers are not allowed in your code snippet, whereas they were absent from your original code excerpt.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

How can I properly assign the final value after applying a discount to prevent undefined index errors?

Developed a new coupon code system for the admin to generate coupons. In the process, there is a need to calculate the final amount to be paid after applying the discount. An if statement was utilized as shown below: if(!empty($discountCode)) { $amou ...

Transferring information from MySQL to Vue.js data attribute

I have retrieved some data from MySQL and I am looking to integrate it into a vue.js data property for seamless iteration using v-for. What is the ideal format to use (JSON or array) and how can I ensure that the data is properly accessible in vue.js? &l ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

What is the best way to have child divs occupy the entire area of the parent div while also accounting for margins

I am facing a challenge with arranging child divs inside a parent div that has a specific width. Even though I am using isotope to arrange them, the layout modes do not work well for me in terms of spacing. My goal is to have the child divs fill the space ...

Securing a JWT token post login

I am new to NodeJS and despite trying numerous solutions, I am facing a challenge. My project involves NodeJS, MongoDB, Express, and Vanilla JS rendered through Pug with an MVC structure. Issue Current Status: I can successfully log in a user and recei ...

Is there a way to create a universal getter/setter for TypeScript classes?

One feature I understand is setting getters and setters for individual properties. export class Person { private _name: string; set name(value) { this._name = value; } get name() { return this._name; } } Is there a w ...

Find the nearest iframe relative to a parent element

I am attempting to find the nearest iframe element to a parent element in order to pinpoint the specific iframe that I want to customize using CSS: <div class ="accroche"> <iframe></iframe> <iframe></iframe> &l ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

Tips for creating a responsive image using Material-UI

I’m facing some challenges in making my page responsive. Specifically, I'm having trouble ensuring that an image remains within the grid container in material UI. Is there a method for making images responsive in this context? Even when I try adding ...

Tips on incorporating jQuery cross-domain functionality

Attempting to retrieve and display the firstName data from this URL: http://www.w3schools.com/jquery/demo_ajax_json.js, as part of a test for another project. Encountered the error message: Origin null is not allowed by Access-Control-Allow-Origin, prompt ...

Summing Up Values in Jquery Loop Through Table Rows

I am facing a challenge with a table that contains a textfield for inputting numeric values. This textfield is part of a repeated row table, with the ID 'amount'. My goal is to calculate the sum of all values entered in the textfields with the ID ...

Can you explain the functionality of $on.constructor in AngularJS?

Recently, I attempted an XSS challenge on the PortSwigger labs website. You can find the challenge here. This is my solution to the XSS challenge: {{$on.constructor('alert(1)')()}} However, since I have no prior experience with AngularJS, I&apo ...

How can I implement a hover effect without triggering a click event?

My structure is pretty basic, here it is: .container { height: 100vh; width: 100%; pointer-events: none; } .click-layer { background-color: #ccc; position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: auto; } .box { ...

Can you determine if the user is holding the CTRL key in a universally recognized way?

Can JQuery or Javascript detect if the user is holding the CTRL key outside of keyPress, keyUp events? Appreciate any insights. Thanks! ...

Navigating Through Tabs in Bootstrap 4

I am currently working on a scrolling tab feature and encountering an issue. I am unable to click on the middle tabs as the scrolling movement is too abrupt when using the right button. How can I adjust the code to allow for a smoother scroll of the tabs? ...

My Discord bot powered by Discord.js is being unresponsive to commands

Hello, I'm facing a major issue with my command handler that I've been struggling with for a while now. The problem is that my bot doesn't respond when I try to use a command. I've tried various methods from YouTube but none of them see ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Adjust the JavaScript variable upon pressing the "c" key

I'm trying to figure out how I can toggle the value of variable x in JavaScript when the key "c" is pressed. Specifically, I want x to change from 0 to 1 when "c" is pressed and revert back to 0 when it's released. I have already defined and name ...

Learn the process of utilizing signed URLs in conjunction with ReactJS to securely store files in AWS

I am currently working on a form where I need to attach images along with regular text inputs in order to submit data to my MongoDB. Here is the code for my post creation function: const [postData, setPostData] = useState({ text: '', i ...