Sooraj Chandran Sooraj Chandran - 6 months ago 39
jQuery Question

Adding labels on force diagram d3 js

I'm trying to add labels to a force graph that is created dynamically. Here is the code.

This is the relevant part of the code where I add the text elements.

labels =;


.attr("text-anchor", "middle")
.attr("x", 0)
.attr("dy", 16)
.attr("startOffset", "50%")
.attr("xlink:href", function(d,i){ return "#id" + i})

Here is a fiddle I created that demonstrates the problem. -

(Since its large
does not allow me to create the code snippet of that size )

If i click the add button a node will be created and a connecting line can be drawn by dragging from one node to another. To move around a node use ctrl + drag.

I'm trying to add the label and the text element is getting added. But it always takes up 0 height and width and ends up at top left corner of the screen. What am i doing wrong ?


You missed to set the ID to the path elements. Try this way.

    .attr('class', 'link')
    .attr("id",function(d, i) {
      return "id" + i; //Sets id to the path elements which will be used in textPaths later
    .classed('selected', function(d) {
      return d === selected_link;
    .style('marker-start', function(d) {
      return d.left ? 'url(#start-arrow)' : '';
    .style('marker-end', function(d) {
      return d.right ? 'url(#end-arrow)' : '';
    .on('mousedown', function(d) {
      if (d3.event.ctrlKey) return;

      // select link
      mousedown_link = d;
      if (mousedown_link === selected_link) selected_link = null;
      else selected_link = mousedown_link;
      selected_node = null;

Updated fiddle