Accepted answer

If I'm understanding you correctly, it would be simpler to append the rectangle, append the text, then size the rectangle to the text:

<!DOCTYPE html>

    <script src=""></script>

    <svg width="900" height="900"></svg>
      var svg ='svg');
      var rect = svg.append("rect")
        .style("fill", "black")
        .attr("x", 20)
        .attr("y", 20);
      var text = svg.append("text")
        .text("Now is the time for all good men to come to the aid of their country")
        .attr("x", 20)
        .attr("y", 20)
        .style("font-family", "arial")
        .style("font-size", "14pt")
      var bbox = text.node().getBBox();
      rect.attr("width", bbox.width);
      rect.attr("height", bbox.height);


Related Query