title: Adding Dynamic Node in D3 Tree
body: <p>Im learning d3 js layout and having difficulty in adding node to the tree layout.</p>
  
  <p>Hoping for a way of adding dynamic node(children) after clicking the parent node.</p>
  
  <p>My current implementation do add the node, but instead of updating it, it added new children and keep the child from before. </p>
  
  <p>Can someone help me understand the problem and a correct way of approaching this.</p>
  
  <p>Here is my code and my <a href="https://jsfiddle.net/fretwiz/5rf9rmq6/" rel="nofollow">Fiddle</a> (click on the root node):</p>
  
  <p>HTML</p>
  
  <pre><code>&lt;div id="body"&gt; 
  &lt;/div&gt;
  &lt;script src="https://d3js.org/d3.v3.min.js" charset="utf-8"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>JS</p>
  
  <pre><code>var margin = {top: 100, right: 50, bottom: 100, left: 50},
      width = 900 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
  
  
  var tree = d3.layout.tree()
      .separation(function(a, b) { return a.children === b.children ? 1 : 1.2; })
      .size([width, height]); 
  
   var svg = d3.select("body")
      .attr("bgcolor", "#fff")
      .append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  
  var dataOne = {
    "name": "Mike and Marcia",
    "children": [
      {
        "name": "Children",
        "children": [
          { "name": "Mikael" }
        ]
      }
    ]
  };
  
  var drawTree = function(source){
  
   var nodes = tree.nodes(source);
   var node = svg.selectAll(".node")
      .data(nodes)
      .enter()
      .append("g");
  
   var boxes = node.selectAll('g')
              .data(nodes)
              .enter()
              .append('g')
              .append('rect')
              .attr("width", 50)
              .attr("height", 40)
              .attr("fill", "tan")
              .attr("x", function(d) { return d.x; })
              .attr("y", function(d) { return d.y + 50; });
  
  
    boxes.on("click", function(d,i){
     clickOutside(d);
    });
  
  
  };
  
  var clickOutside = function(value){
    var newData = {
          "name": "Mike and Marcia",
          "children": [{
              "name": "Children",
              "children": [{
                  "name": "Mikael"
              }]
          },{
              "name": "Pets",
              "children": []
          }]
       };
  
   drawTree(newData);    
   console.log(value);
  
  }
  
  drawTree(dataOne);
  </code></pre>