title: Adding data dynamically in Cytoscape.js
body: <p>My setup is to have a graph online, and then get a new graph (via Ajax calls to a server) and use it to update the online graph. For example, I may want to include only those nodes that are in both graphs. </p>
  
  <p>I would like to use the built-in set functions (here: <a href="http://js.cytoscape.org/#collection/building--filtering" rel="nofollow">http://js.cytoscape.org/#collection/building--filtering</a>) for manipulating the old and new graphs, but I need two collections to do it. If I add the new graph to the <code>cy</code> object collection, then the nodes are drawn immediately, and I can't reference them as a new collection. </p>
  
  <p>My solution was to have a separate <code>cy</code> object and then use set operations between these two collections. But as my example shows, it's not working as expected. It's not just animation, that's a just a toy use case. I may want to remove those nodes, or move them to a specific location.</p>
  
  <p>For some reason, this doesn't work. Namely, <code>just2</code> is not colored blue as I would hope. Can anyone explain why not, and what I need to do to fix it?</p>
  
  <pre><code>var cy = cytoscape({
  
      container: document.getElementById('cy'), // container to render in
  
      style: [ // the stylesheet for the graph
          {
              selector: 'node',
              style: {
                  'background-color': '#666',
                  'label': 'data(id)'
              }
          },
      ],
  
      elements: {
          nodes: [
              { data: { id: 'n0' } },
              { data: { id: 'n1' } },
              { data: { id: 'n2' } },
  
          ],
              edges: [
              { data: { source: 'n0', target: 'n1' } },
              { data: { source: 'n1', target: 'n2' } }
          ]
      },
      layout: {
          name: 'grid'
      },
  
  });
  
  // Add new data here -- potentially the result of an Ajax call.
  var newarray = [
      { data: { id: 'n0' } },
      { data: { id: 'n8' } },
      { data: { id: 'n9' } },
      { data: { source: 'n8', target: 'n9' } },
  ];
  
  var cy2 = cytoscape(
      {
          elements: newarray,
          headless: true,
          renderer: { name: null }
      });
  
  var el = cy.elements();
  var cy2el = cy2.elements();
  
  var both = el.intersection(cy2el);
  var justel = el.difference(cy2el);
  var just2 = cy2el.difference(el);
  
  cy.add(cy2el);
  
  // This works.
  both.animate({
      style: { "background-color" : "yellow" }
  }, {
      duration: 500,
  });
  
  // This works. 
  justel.animate({
      style: { "background-color" : "red" }
  }, {
      duration: 500,
  });
  
  // This does not work.
  just2.animate({
      style: { "background-color" : "blue" }
  }, {
      duration: 500,
  });
  </code></pre>