title: D3v4 inserting new nodes
body: <p>EDIT: <a href="http://codepen.io/mrelemental/pen/vabBNz" rel="nofollow noreferrer">added codepen example</a></p>
  
  <p>I'm experimenting with D3v4 force simulation, but I am currently unable to properly add new nodes to a graph. Here's the setup</p>
  
  <pre><code>var svgRef = d3.select("body").append("svg")
      .attr("width",svgWidth)
      .attr("height",svgHeight)
      .on("mousedown",svgClick);
  
  var nodes_data = [{id: "0"},{id: "1"},{id: "2"}];
  var links_data = [{source:"1",target:"2"}];
  
  var linksRef = svgRef
      .selectAll(".link")         
      .data(links_data).enter()
      .append("line").attr("class", "link");
  
  var nodesRef = svgRef
      .append("g").attr("class", "nodes")
      .selectAll(".node")
      .data(nodes_data).enter()
      .append("g").attr("class", "node")
      .call(d3.drag()...);
  
  nodesRef.append("circle")
      .attr("r", nodeRadius);
  </code></pre>
  
  <p>I'm creating a group for individual nodes to hold their <code>circle</code> and <code>title</code> and <code>text</code> etc. and all these nodes are created under a greater "nodes" group. The end result looks like this:</p>
  
  <pre><code>&lt;svg&gt;
      ...
      &lt;g class="nodes"&gt;
          &lt;g class="node"&gt;
              &lt;circle&gt;
              &lt;text&gt;
              ...
          &lt;/g&gt;
          &lt;g class="node"&gt;&lt;/g&gt;
          &lt;g class="node"&gt;&lt;/g&gt;
          ...
      &lt;/g&gt;
  &lt;/svg&gt;
  </code></pre>
  
  <p>Then I'm adding a new node to my data and <em>trying</em> to insert it in the graph</p>
  
  <pre><code>function svgClick(){
  
      // add new node
      nodes_data.push({id: nodeCount++, "x":d3.event.X, "y":d3.event.y});
  
      // restart simulation
      simulation.nodes(nodes_data).on("tick", ticked);
  
      // insert new nodes
      nodeEnter = svgRef
          .selectAll(".node")
          .data(nodes_data).enter()
          .append("g").attr("class", "node")
          .call(d3.drag()...)
          .append("circle")
              .attr("class", "node")
              .attr("r", nodeRadius);
  
      // merge new nodes
      nodesRef = nodeEnter.merge(nodesRef);
  }
  </code></pre>
  
  <p>2 things that are going wrong that I'm unable to fix:</p>
  
  <ul>
  <li><p><strike>the inserted node does not appear at the mouse coordinates</strike>
  <em>Figured this one out, just a typo in <code>d3.event.X</code> where <strong>X</strong> had to be lowercas</em></p></li>
  <li><p>the inserted node is not added in the <code>&lt;g class="nodes"&gt;</code> but below. I can't find a way to select it properly</p></li>
  </ul>
  
  <p>Like so:</p>
  
  <pre><code>&lt;svg&gt;
      &lt;g class="nodes"&gt;
          &lt;g class="node"&gt;&lt;/g&gt;
          &lt;g class="node"&gt;&lt;/g&gt;
      &lt;/g&gt;
      &lt;g class="node"&gt;&lt;/g&gt;  // &lt;--- inserted here
  &lt;/svg&gt;
  </code></pre>