text elements not visible when appended from function

Viewed 40

I want to add text to my d3 visualization using a function in append() function. But even the resulting DOM is exactly as when adding text static (passing the text directly to append()) it is not visible on the svg canvas.

var svg = d3.select("body").append("svg");
svg.attr("width", 800);
svg.attr("height", 600);

svg.selectAll("g.m1").data([1, 2, 3])
  .enter()
  .append("g")
  .attr("class", "m1")
  .attr("transform", "translate(50,50)")
  .append("text")
  .attr("dy", function(d) {
    return d + ".0em"
  })
  .text(function(d) {
    return "Hello world directly: " + d;
  });

svg.selectAll("g.m2").data([1, 2, 3])
  .enter()
  .append("g")
  .attr("class", "m2")
  .attr("transform", "translate(50,150)")
  .append(function(d) {
    var t = d3.create("text");
    t.attr("dy", d + ".0em")
      .text("Hello world via function: " + d);
    return t.node();
  });
svg {
  border: 3px solid red;
}

text {
  fill: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

In output I only see the text in the "m1" texts and not the "m2" texts. Even the output HTML is exactly the same: https://imgur.com/a/2xusuPD

1 Answers

If you're creating a disconnected SVG element, you must supply a namespace i.e. svg:text rather than just text.

var svg = d3.select("body").append("svg");
svg.attr("width", 800);
svg.attr("height", 600);

svg.selectAll("g.m1").data([1, 2, 3])
  .enter()
  .append("g")
  .attr("class", "m1")
  .attr("transform", "translate(50,50)")
  .append("text")
  .attr("dy", function(d) {
    return d + ".0em"
  })
  .text(function(d) {
    return "Hello world directly: " + d;
  });

svg.selectAll("g.m2").data([1, 2, 3])
  .enter()
  .append("g")
  .attr("class", "m2")
  .attr("transform", "translate(50,150)")
  .append(function(d) {
    var t = d3.create("svg:text");
    t.attr("dy", d + ".0em")
      .text("Hello world via function: " + d);
    return t.node();
  });
svg {
  border: 3px solid red;
}

text {
  fill: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Related