d3 way to move nodes in DOM

I was wondering if there is a d3 way to move nodes in DOM.

For example, in this how can I select the class body > svg > g > g.fake and move that on top of class body > svg > g > g.movingObjText in DOM so that it results in following

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
  <body>
    <div id="container"></div>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
      <rect class="vBoxRect" width="1280" height="720" fill="#00b140" stroke="red"></rect>
      <rect class="boundRect" x="70" y="70" width="1020" height="600" fill="none" stroke="#00b140"></rect>
      <g class="bound" style="transform: translate(70px, 70px);">
        <g class="valLine">
          <path class="Australia" id="valLine" d="M0,600L42.5,600L85,334.0399725781784L127.5,313.86735572781834L212.5,222.9985644559286L255,222.9985644559286L297.5,248.66379557852153L340,248.66379557852153L382.5,248.66379557852153L425,171.66810221073513L467.5,171.66810221073513L510,146.00287108814229L552.5,248.66379557852153L595,248.66379557852153L637.5,248.66379557852153L680,197.33333333333186L722.5,197.33333333333186L765,171.66810221073513L807.5,94.67240884294881L850,94.67240884294881L892.5,94.67240884294881L935,25.495262704563594L977.5,25.495262704563594L1020,0" stroke="black" fill="none" stroke-dasharray="1541.6458740234375 1541.6458740234375"></path>
        </g>
        <g class="fake">
          <rect fill="white" rx="2.5" x="1014.7325439453125" y="-15.802469253540039" width="43.73328399658203" height="21.06995964050293"></rect>
        </g>
        <g class="movingObjText">
          <text x="1020" y="0">31.13</text>
        </g>
      </g>
    </svg>
  </body>
  <script type="text/javascript"></script>
</html>

Thank you in advance.

It looks to me like g.fake is on top of g.movingObjText, which is why you can’t see the text. If you want to programmatically take g.movingObjText to the top of it’s group, you should use the following in a separate cell:

d3.select(div).select('g.movingObjText').raise()

Of course, you’ll first need to assign the name div to the cell you want to modify.

1 Like

@mcmcclur Thanks for this and I have a question reg. selection.raise().

As per the documentation, Re-inserts each selected element, in order, as the last child of its parent

In my case, the DOM is like this before using raise

After using raise d3.select('body > svg > g > g.movingObjText').raise();, it becomes following. But it is still not the last child of its parent.

.

There’s no way to know why, without seeing code. Here’s an implementation in Observable where you can actually see the nodes moving in the formatted SVG in response to a programmatic call to selection.raise():