Nodes & edges
This chapter will introduce how to perform basic operations on nodes and edges in Cytoscape.js, including adding, deleting, updating elements, as well as element traversal and collection operations.
Open a standalone demo to switch between the live preview and its source files:
Vanilla JavaScript · React · Cytocausal
Initialize Graph Instance
First, let’s create a graph instance with initial nodes and edges:
const cy = cytoscape({
container: document.getElementById("cy"),
elements: [
// Initial nodes
{ data: { id: "a", label: "Node A", weight: 75 } },
{ data: { id: "b", label: "Node B", weight: 65 } },
// Initial edges
{
data: {
id: "ab",
source: "a",
target: "b",
label: "Edge AB",
weight: 1.5,
},
},
],
style: [
{
selector: "node",
style: {
"background-color": "#666",
label: "data(label)",
"text-valign": "center",
"text-halign": "center",
width: "data(weight)", // Use data property to control style
height: "data(weight)",
},
},
{
selector: "edge",
style: {
width: "data(weight)", // Use data property to control style
"line-color": "#999",
label: "data(label)",
"curve-style": "bezier",
"target-arrow-shape": "triangle",
},
},
{
selector: ":selected",
style: {
"background-color": "#900",
"line-color": "#900",
"target-arrow-color": "#900",
"source-arrow-color": "#900",
},
},
],
layout: { name: "grid" },
});Element Operations
Adding Elements
Add Single Node
function addNode() {
const id = "node-" + Date.now();
cy.add({
group: "nodes",
data: {
id,
label: `Node ${id}`,
weight: Math.random() * 50 + 50, // Random weight
},
position: {
// Can specify position
x: Math.random() * 300 + 150,
y: Math.random() * 200 + 100,
},
selected: true, // Can set initial state
classes: ["new-node"], // Can add classes
});
}Batch Add Elements
function addMultipleElements() {
cy.add([
{ group: "nodes", data: { id: "n1" } },
{ group: "nodes", data: { id: "n2" } },
{ group: "edges", data: { id: "e1", source: "n1", target: "n2" } },
]);
}Deleting Elements
Delete Selected Elements
function removeSelected() {
cy.$(":selected").remove();
}Conditional Deletion
function removeByCondition() {
// Delete all isolated nodes
cy.$("node[[degree = 0]]").remove();
// Delete specific types of edges
cy.$("edge[weight < 1]").remove();
}Updating Elements
Update Data
function updateElementData() {
// Update single property
cy.$("node:selected").forEach((node) => {
const newLabel = prompt("Enter new label:", node.data("label"));
if (newLabel) {
node.data("label", newLabel);
}
});
// Batch update multiple properties
cy.$("node:selected").data({
weight: 100,
type: "updated",
timestamp: Date.now(),
});
}Update Position
function updatePosition() {
cy.$("node:selected").position({
x: 100,
y: 100,
});
}Element Traversal and Collections
Basic Selectors
// Select all nodes
const allNodes = cy.nodes();
// Select all edges
const allEdges = cy.edges();
// Select element by specific ID
const nodeA = cy.$("#a");
// Select elements by class
const newNodes = cy.$(".new-node");
// Select elements with specific data attributes
const heavyNodes = cy.$("node[weight >= 75]");Traversal Operations
// Traverse all neighboring nodes
function traverseNeighbors(nodeId) {
const node = cy.$(`#${nodeId}`);
node.neighborhood().forEach((ele) => {
console.log(ele.data());
});
}
// Traverse all connected edges
function traverseConnectedEdges(nodeId) {
const node = cy.$(`#${nodeId}`);
node.connectedEdges().forEach((edge) => {
console.log(edge.data());
});
}
// Get path
function getPath(sourceId, targetId) {
const path = cy.$(`#${sourceId}`).shortestPath(cy.$(`#${targetId}`));
return path;
}Collection Operations
// Union collections
const collection1 = cy.$(".type1");
const collection2 = cy.$(".type2");
const combined = collection1.union(collection2);
// Intersection
const intersection = collection1.intersection(collection2);
// Difference
const difference = collection1.difference(collection2);Data Management
Data Storage
// Store data on elements
cy.$("#a").data({
weight: 75,
type: "user",
metadata: {
created: Date.now(),
status: "active",
},
});
// Get data
const weight = cy.$("#a").data("weight");
const metadata = cy.$("#a").data("metadata");Batch Data Operations
// Batch update data
cy.batch(() => {
cy.nodes().forEach((node) => {
node.data("visited", true);
node.data("timestamp", Date.now());
});
});Key Concepts Explanation
-
Element Selectors
cy.$(): Use selectors to find elements:selected: Selected state elementsnode:selected: Selected state nodes[attributeName]: Attribute selectors.className: Class selectors#id: ID selectors
-
Element Data
data: Store element data (e.g., id, label, etc.)position: Node position information (nodes only)scratch: Temporary data storage (not serialized)
-
Element Operations
cy.add(): Add new elementsremove(): Delete elementsdata(): Get or set element dataposition(): Get or set node positionmove(): Move node position
-
Collection Operations
union(): Merge collectionsintersection(): Get intersectiondifference(): Get differencefilter(): Filter elementsnot(): Exclude elements
-
Traversal Methods
neighborhood(): Get neighboring elementsconnectedEdges(): Get connected edgespredecessors(): Get predecessor nodessuccessors(): Get successor nodescomponents(): Get connected components
-
Performance Optimization
- Use
cy.batch()for batch operations - Cache frequently used selector results
- Use
eles.forEach()instead offorloops - Use event delegation appropriately
- Use
Keep edits in the causal dataset
Native cy.add, cy.remove and data calls below belong to the standalone playground. In a Cytocausal app, update snapshot nodes and edges in React, or use CausalEditor. Direct renderer mutations do not update the dataset used by analysis and may be overwritten on synchronisation.