Adding additional text will not render d3.js' output

I'm struggling with a simple issue here,

My goal is to add a div to my svg element containing text. I have written the code for this and in the DOM, it shows that the svg has the correct class attached along with the desired text. However, the text is not displaying on the page.

I'm hoping someone can help me identify where I've made a mistake?

Here is the snippet of the code;

http://plnkr.co/edit/LxD1TarajR8dZUS7MbHg?p=preview

var vis = d3.select("#chart").selectAll("svg")
  .data(dataset)
  .enter()
  .append('svg')
  .attr("class", "svgCircle") // Adding svg class
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

vis.append("circle")
  .attr("fill", "#ffffff")
  .attr("stroke", "#dfe5e6")
  .attr("stroke-width", 1)
  .attr('r', width / 2)

d3.selectAll(".svgCircle") // Append label to circles
  .append("div")
  .attr("class", "circleLabel")
  .append("text")
  .text(function(d) {
    return d.label
  })

Answer №1

According to @RobertLongson, the only way to insert html into an svg is with foreignObject, but this method doesn't work in IE.

Instead of that, I recommend using pure svg elements.

See the outcome here: http://plnkr.co/edit/rb18RQTT7tBeo8lJXVpO?p=preview

d3.selectAll(".svgCircle")
  .append("text")
  .text(function(d) {
    return d.label
  })
  .style("stroke","black")
  .attr("dy", "1em");

You have full control over all text attributes, unlike your previous comment about having more control over text positioning. I just demonstrated setting the dy and stroke attributes, but you can customize the color and shape of your text in any way you desire.

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

Is there a way to add a scrollbar to the ChartJS tooltip to avoid data

I'm currently working on a chartJS project where I have a callback function to display data in tooltips. However, as the data increases, the overflow section of the tooltip gets hidden from the canvas. Is there a solution to prevent this overflow and ...

Send the form data from a modal controller in AngularJS to an ng-controller outside of the modal

There seems to be a confusion with the functionality not working as expected: In my Angular application, I have a main page with an ng-controller named "SearchCtrl" that handles sending search requests to a webserver. app.controller('SearchCtrl&apos ...

Embrace the presence of null values on the client side

When utilizing the code below, I can determine the location of logged-in users. However, there are some users who do not have a specific location assigned. For example, Administrators are common for all locations. In such cases, how can I set it so that ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

What method can I use to ensure that the sidebar stays fixed at a particular div as the user continues to scroll down the

Is there a way to automatically fix the sidebar once the user scrolls down and hits the top of the .Section2? Currently, I have to manually enter a threshold number which can be problematic due to varying positions across browsers and systems. Fiddle htt ...

Swap out a component for another using a higher order component (HOC perhaps?)

I have noticed that certain libraries like "framer-motion" in react utilize this syntax, for instance to include an animated H1: <motion.h1> where the h1 tag is enhanced with animations specified in the component's props. What confuses me is ho ...

Experiencing difficulties integrating react-moveable with NEXTjs: Error encountered - Unable to access property 'userAgent' as it is undefined

I've been grappling with this problem for the past few hours. I have successfully implemented react-moveable in a simple node.js app, but when I attempt to integrate it into a NEXTjs app, an error crops up: TypeError: Cannot read property 'userAg ...

Manipulating deeply nested state data in Vuex actions can be a challenge

When working in the store, I have an action that updates certain data. The action is structured like this: setRoomImage({ state }, { room, index, subIndex, image }) { state.fullReport.rooms[room].items[index].items[subIndex].image = image; co ...

The error in React's useEffect occurs when trying to access the property 'map' of an undefined value

import { handleResponse, handleError } from "./apiUtils"; const baseUrl = process.env.REACT_APP_API_URL; export function getAllNotes() { return fetch(baseUrl + "/notes", { method: "GET", headers: { 'Accept': 'application/j ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Color-Thief Node plugin reported an issue: "The provided image has not finished loading."

While working in Node/Express, I attempted to utilize the npm package color-thief to extract the dominant color from an image. Unfortunately, it failed with the error message stating that the "image given has not completed loading". The intriguing part is ...

Storing an array in a cookie using Angular 8

Currently, I am utilizing the ngx-cookie-service package. { "user": [ { "id": 109, "name": "name1", "job" : "job name" } ], "token":"xxxx" } this.cookieService.set( 'user_id', ...

Interactive planetary visualization using three.js in real-time

As I work on my react project, I'm developing a globe and looking to initialize it accurately with respect to a specific time, whether it be the current time or a future time. The goal is for this globe to correctly align itself with the day and night ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

Is it possible for Netbeans 7.3 to debug a PHP script when triggered by a JSON request?

In my Netbeans 7.3.1 setup, I usually have no issues debugging PHP files with Xdebug when my site project is structured to generate the site directly from PHP code. However, I'm currently working on a site that consists mostly of HTML files and only h ...

Should Bower and Grunt Be Installed Globally or Locally?

When it comes to installing packages globally, we typically avoid it due to the possibility of working on multiple projects simultaneously that require different versions of the same libraries. However, there seems to be conflicting information regarding t ...

Align the position of two divs with matching IDs (#thumb-1 equals #project-1) using JavaScript or jQuery, but without the use of jQuery UI

I am currently working on creating a portfolio gallery and have put together the following HTML structure: <article class="work-gallery"> <ul> <li id="project-1"><img src="http://placehold.it/50x00"></li> ...

Find the sum and subtotals for two different categories in a JavaScript array

Currently, I'm in the process of aggregating three totals: totalPoints, monthlyTotals, and monthlyByType by utilizing Array.prototype.reduce. So far, I've managed to successfully calculate totalPoints and monthlyTotals, but I'm encountering ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

Obtaining input value when button is clicked

I am currently working on a feature where, upon clicking the Submit button, I aim to retrieve the value entered into the input field in order to update the h1 element. import React from "react"; function App() { const [headingText, setHeadingT ...