title: How can I dynamically resize an SVG rect based on text width?
body: <p>In an SVG graph I create node elements consisting of a rectangle and some text. The amount of text can differ significantly, hence I'd like to set the width of the rect based on the width of the text.</p>
  
  <p>Here's the creation of the rectangles with D3.js (using fixed width and height values):</p>
  
  <pre><code>var rects = nodeEnter.append("rect")
      .attr("width", rectW)
      .attr("height", rectH);
  </code></pre>
  
  <p>followed by the text element:</p>
  
  <pre><code>var nodeText = nodeEnter.append("text")
      .attr("class", "node-text")
      .attr("y", rectH / 2)
      .attr("dy", ".35em")
      .text(function (d) {
          return d.data.name;
      });
  nodeText // The bounding box is valid not before the node addition happened actually.
      .attr("x", function (d) {
          return (rectW - this.getBBox().width) / 2;
      });
  </code></pre>
  
  <p>As you can see, currently I center the text in the available space. Then I tried to set the widths of the rects based on their text, but I never get both, the rect element and the text HTML element (for getBBox()) at the same time. Here's one of my attempts:</p>
  
  <pre><code>rects.attr("width",
          d =&gt; this.getBBox().width + 20
      );
  </code></pre>
  
  <p>but obviously <code>this</code> is wrong as it refers to <code>rects</code> not the text.</p>
  
  <p>What's the correct approach here?</p>