# GraphObject Manipulation

## Programmatically interacting with Nodes

This guide will show you some basic ways of programmatically interacting with GoJS nodes and links and model data. Throughout this page, we will use the following diagram setup as our starting point:

    const myDiagram =
      new go.Diagram("myDiagramDiv", { "undoManager.isEnabled": true });

    // define a simple Node template
    myDiagram.nodeTemplate =
      new go.Node("Auto")
        .add(
          new go.Shape("Rectangle",
              // don't draw any outline
              { stroke: null })
            // the Shape.fill comes from the Node.data.color property
            .bind("fill", "color"),
          new go.TextBlock(
              // leave some space around larger-than-normal text
              { margin: 6, font: "18px sans-serif" })
            // the TextBlock.text comes from the Node.data.key property
            .bind("text")
        );

    myDiagram.model = new go.GraphLinksModel(
      [
        { key: 1, text: "Alpha", color: "lightblue" },
        { key: 2, text: "Beta", color: "orange" },
        { key: 3, text: "Gamma", color: "lightgreen" },
        { key: 4, text: "Delta", color: "pink" }
      ]);

The code produces this Diagram:

## Finding single nodes: Diagram.findNodeForKey

You can use `Diagram.findNodeForKey(key)` to get a reference to a Node in JavaScript. Key values in GoJS can be either strings or numbers. You can then use the Node reference to inspect and manipulate the Node.

    const node = myDiagram.findNodeForKey(1);

    // Selects the node programmatically, rather than clicking interactively:
    myDiagram.select(node);

    // Outputs a JavaScript object in the developer console window.
    // The format of what is output will differ per browser, but is essentially the object:
    // { key: 1, text: "Alpha", color: "lightblue" }
    // plus some internal implementation details.
    console.log(node.data);

However `findNodeForKey` may return `null` if no node data uses that key value. Also, it only looks at the model data to find a node data that uses the given key value, from which it finds the corresponding Node in the Diagram. It does not look at the text values of any TextBlocks that are within the Nodes, so it can work even if no text is shown at all. And it does not look at any programmatically added Nodes that were not created from model data.

Once you have a `Node`, you can get its key either via the `Node.key` property or by looking at its data: `someNode.data.key`, just as you can look at any of the data properties.

## Collections of Nodes and Links

Diagrams have several properties and methods that return iterators describing collections of Parts. Both Nodes and Links are kinds of Parts. `Diagram.nodes` and `Diagram.links` return iterators of all Nodes and Links in the Diagram, respectively. `Diagram.selection` returns an iterator of selected Parts (both selected Nodes and selected Links).

There are also more specific methods for common operations, such as `Diagram.findTreeRoots()` which returns an iterator of all top-level Nodes that have no parent nodes.

This next example uses `Diagram.nodes` and shows how to iterate over the collection.

    // Calling Diagram.commit executes the given function between startTransaction and commitTransaction
    // calls.  That automatically updates the display and allows the effects to be undone.
    myDiagram.commit(d => {  // d === myDiagram
      // iterate over all nodes in Diagram
      d.nodes.each(node => {
        if (node.data.text === "Beta") return; // skip Beta, just for contrast
        node.scale = 0.4; // shrink each node
      });
    }, "decrease scale");

As a result we have very scaled-down nodes, except for Beta:

## Named GraphObjects and Panel.findObject

Often we want to manipulate a property that belongs to one of the Node's elements, perhaps an element arbitrarily deep in the template. In our example Diagram, each Node has one Shape, and if we want to change the color of this Shape directly we would need a reference to it. To make it possible to find, we can give that Shape a name:

    myDiagram.nodeTemplate =
      new go.Node("Auto")
        .add(
          new go.Shape("Rectangle",
              { stroke: null, name: "SHAPE" }), // added the name property
            .bind("fill", "color"),
          new go.TextBlock({ margin: 6, font: "18px sans-serif" }),
            .bind("text")
        );

Names allow us to easily find GraphObjects inside of Panels (all Nodes are also Panels) using `Panel.findObject`, which will search the visual tree of a Panel starting at that panel. So when we have a reference to a Node, we can call `someNode.findObject("SomeName")` to search through the node for a GraphObject with that name. It will return a reference to the named GraphObject if it is found, or `null` otherwise.

Using this, we could make an HTML button that changes the fill of the Shape inside of a selected Node:

    const selectionButton = document.getElementById("selectionButton");
    selectionButton.addEventListener("click", () => {
      myDiagram.commit(d => {
        d.selection.each(node => {
          const shape = node.findObject("SHAPE");
          // If there was a GraphObject in the node named SHAPE, then set its fill to red:
          if (shape !== null) {
            shape.fill = "red";
          }
        });
      }, "change color");
    });

## Changing Properties and Updating the Model using Data Bindings

Looking again at our Node template, we have the `Shape.fill` property data-bound to the "color" property of our Node data:

    myDiagram.nodeTemplate =
      new go.Node("Auto")
        .add(
          new go.Shape("Rectangle", { stroke: null, name: "SHAPE" })
            .bind("fill", "color"),  // note this data binding
          new go.TextBlock({ margin: 6, font: "18px sans-serif" })
            .bind("text")
        );

Changing the Shape's `fill` property inside our node will not, as the Node template currently stands, update the model data.

    const node = myDiagram.findNodeForKey(1);
    const shape = node.findObject("SHAPE");
    shape.fill = "red";

    // outputs "lightblue" - the model has not changed!
    console.log(node.data.color);

This is undesirable in some cases. When we want the change to persist after saving and loading, we will want the model data updated too.

However, in some situations this lack of persistence might be a good thing. For instance if we want the color change for only cosmetic purposes, such as changing the color of a button when hovering over it with the mouse, we would not want to modify the model data that might be saved.

For now, suppose that we do want to update the model. The preferred way to do this is to modify the data in the model and depend on the data binding to automatically update the Shape. However, we cannot modify the data directly by just setting the JavaScript property.

    const node = myDiagram.findNodeForKey(1);

    // DO NOT DO THIS!
    // This would update the data, but GoJS would not be notified
    // that this arbitrary JavaScript object has been modified,
    // and the associated Node will not be updated appropriately
    node.data.color = "red";

Instead we should set the data property using the method `Model.set(data, propertyName, propertyValue)`. As always, changes should always be performed within a transaction. There should only be a single transaction for all changes that need to be made at the same time, from the user's point of view. A convenient way to perform a transaction is to call `Model.commit`.

    const node = myDiagram.findNodeForKey(1);

    // Model.commit executes the given function within a transaction
    myDiagram.model.commit(m => {  // m == the Model
      // This is the safe way to change model data.
      // GoJS will be notified that the data has changed
      // so that it can update the node in the Diagram
      // and record the change in the UndoManager.
      m.set(node.data, "color", "red");
    }, "changed color");

    // outputs "red" - the model has changed!
    console.log(node.data.color);
    // and the user will see the red node

Note that there is no longer any need to name the Shape "SHAPE", because there is no longer any need to call `findObject` to look for the particular Shape. Data binding will automatically update properties, so we do not have to do that ourselves.

    myDiagram.nodeTemplate =
      new go.Node("Auto")
        .add(
          new go.Shape("Rectangle", { stroke: null })  // removed the name property
            .bind("fill", "color"),
          new go.TextBlock({ margin: 6, font: "18px sans-serif" })
            .bind("text")
        );

## Subjects Mentioned and Further Reading

- Data Binding — See the intro page on Data Binding for lots more detail.
- Transactions — See the intro page on Transactions.
- `console.log` — A powerful debugging aid that is part of most browser's developer tools. See the Chrome guide or the Firefox guide for their respective developer consoles. See more suggestions for debugging GoJS diagrams at the intro page on Debugging.

You may want to read more tutorials, such as the Learn GoJS tutorial. and the Interactivity tutorial. You can also watch tutorials on YouTube.

If you are ready for a comprehensive overview of GoJS, have a look at the technical introduction. If you want to explore by example, have a look at the samples to get a feel for what's possible with GoJS.