Is there a way to add additional text to a text element within an SVG?

Is it possible to append a new text element at the end of the data label by clicking on that particular text? I have attempted to implement this in my code but the additional text is not being displayed as expected:

circleGroup.selectAll("text")
           .data(data)
           .enter()
           .append("text")
           .text(function (d) {
                if (d.label) {
                    return d.label;
                }
                   return "";
                })
           .attr("x", function (d) {
                  return x(d.time) + 6;
            })
           .attr("y", function (d) {
                    return y(d.plotY) + 4;
                })
           .attr("font-size", "10px")
           .attr("fill", "#2d3d45")
           .on("click", function(d) {
                    d3.select(this).append("text").text("[A]").attr("x", function(d) {return x(d.time) + 25;}).attr("y", function(d) { return y(d.plotY) + 4;});

           });

Despite appending it to the data label, the "[A]" text is not visible.

https://i.sstatic.net/S8OTJ.png

Why isn't the addition of the "[A]" text displaying properly after being appended to the parent text element?

Answer №1

Simply put, you cannot directly attach a <text> element to another <text> element.

As outlined in the SVG specifications,

A text content child component is essentially a text-based entity that can exist within another text-related entity. In SVG 1.1, these text content children include: ‘altGlyph’, ‘textPath’, ‘tref’ and ‘tspan’.

The workaround involves appending a <tspan> instead:

var svg = d3.select("svg");
svg.append("text")
  .attr("x", 20)
  .attr("y", 20)
  .text("I am the text element")
  .append("tspan")
  .attr("dy", "1.5em")
  .attr("x", 20)
  .text("And I am the tspan element")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

In doing so, your structure will look like this:

<text x="20" y="20">I am the text element
    <tspan dy="1.5em" x="20">And I am the tspan element</tspan>
</text>

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

Guide on Developing a JavaScript Library

After creating several JavaScript functions, I noticed that I tend to use them across multiple projects. This prompted me to take things a step further and develop a small JavaScript Library specifically for my coding needs. Similar to popular libraries l ...

Restrict certain links from being clickable until the page has finished loading and all click events have been bound using

I developed a modal dialog plugin using jquery, designed to link to the click event of each <a> element with a specific class. This modal dialog uses AJAX to 'fetch' a page declared under the 'href' parameter of the <a> el ...

Leverage JSON data within an AngularJS controller

I have a JSON list in Angular that looks like this: vm.allnews = actualNews; After checking it with console.log, I can see that it's working fine and I am able to retrieve all news from the array list. Each news item has a title which I can display ...

The method firebaseApp.auth does not exist in user authentication using Firebase

Implementing user authentication with Firebase in my React webapp has been a challenge due to issues with the firebaseAuth.app() function. Despite trying various solutions such as reinstalling firebase dependencies, updating imports to SDK 9 syntax, and ad ...

Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using: var formData = $('#spec-wip-form, #platingspec-form').serializeArray(); var platingId = @Model.PlatingId; var form = JSON.s ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...

The benefits of utilizing "native tags" instead of foreignObject in an SVG

As the creator of the stackoverflow-readme-profile project, I dedicated extensive time and effort to crafting a personalized Stackoverflow profile in the form of an SVG image. Utilizing "native svg tags," I meticulously constructed elements such as: < ...

Are there any disadvantages to utilizing bindActionCreators within the constructor of a React component when using Redux?

I have come across numerous instances where the bindActionCreators function is used within the mapDispatchToProps function as shown below: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: som ...

Using ReactJS to insert an array of objects into an object nested within another array object

After receiving a response from a REST call, I am working with an array of objects. response.data.steps Here is an example of how it looks: https://i.sstatic.net/h2QsL.png Now, my task is to add a new Object Array to each Child of this array. Can anyo ...

What is the most efficient method for fetching data from the server at regular intervals of 30 minutes?

As I search for a way to automatically update my webpage with fresh data from the server, I am faced with uncertainty regarding the frequency of these updates. The intervals could range anywhere from every 10 minutes to an hour, which makes it challenging ...

What is the process for creating a modal transition?

I am attempting to add animation to a modal using a transition effect. My goal is to open it slowly, either from the center of the screen or from the bottom. However, I am struggling to understand how this can be achieved... While searching on Google, I c ...

Identify a CSS style or attribute that is being dynamically assigned using JavaScript

While using the Jquery Cycle plugin for my slideshow, I'm looking to trigger an event when a specific slide is active. The Cycle plugin handles this by adjusting the opacity of images within a div in this manner: <div style="position: absolute; to ...

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

JavaScript code altered link to redirect to previous link

I added a date field to my HTML form. <input type="date" name="match_date" id="matchDate" onchange="filterMatchByDate(event)" min="2021-01-01" max="2021-12-31"> There is also an anchor tag ...

Problem with jQuery AJAX Request Resolving JSON Data

One thing I have on my first page is this function: <script> function update() { $("#notice_div").html('Loading..'); $.ajax({ type: 'GET', dataType: 'json', data: latestid, url: '2includejso ...

"Learn how to easily format specific characters in JavaScript using the text plugin to create bold text strings with a unique

I would like to transform this text into something like "|| something 1 || something 2 || more || last one ||" and then make all of that string bold by adding "|" around it then it would look like this "|| something 1 || something 2 || more || last one | ...

When using React, my goal is to preserve state even after the page is refreshed

I am facing an issue in React where I want to persist state even after refreshing the page. I attempted to use localStorage, but every time the page is refreshed, the data gets cleared. function App() { const [selected, setSelected] = useState() con ...

Tips for utilizing the setInterval function in javascript to update the background color of the body

Currently, I am tackling a project for my course and I am seeking to modify the body's background color on my website randomly by leveraging the setInterval technique in my JavaScript file. Any suggestions on how to achieve this task? ...

What is the method for concatenating two strings in JavaScript without any whitespace in between?

When working with two strings involving time, consider the following scenario: var gettime= $("#select-choice-2 :selected").text(); The above code returns a time value in 24-hour format, such as 17:45 However, if you require the time to display in the ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...