// Add elements to the graph and return them as a collection
cy.add(input: | ElementsInput<NodeData, EdgeData> | Iterable<ElementDefinition<NodeData | EdgeData>>): Collection<NodeData, EdgeData>Add elements to the graph and return them as a collection.
Takes all three input forms: the element-definition form (one object, an array, or { nodes, edges }), the columnar bulk form (typed-array columns with edge endpoints as node indices), and the binary wire buffer produced by serializeElements/cy.serialize(). Nodes are added before edges, so an edge may reference a node added in the same call. Wire and columnar inputs may carry miniature state with current positions; adding them does not rescale those coordinates.
Fires an add event per element. Inside a batch the first style application of the new elements defers to the outermost endBatch(), so style-derived reads (width(), label()) may be stale until then.
Graph-level data() in a wire buffer is ignored here, where options.elements applies it: adding elements to a populated graph must not overwrite that graph's own data(). Apply it explicitly with cy.data( deserializeElements( buf).data) if that is what you want.
Any iterable of element definitions is accepted too — a generator, a Set, a Map's values() — and is read once into an array, then added exactly as that array would be. A wire buffer's typed-array view is iterable as well, and is decoded as a wire payload, never walked as definitions.
| Name | Description |
|---|---|
input: | ElementsInput<NodeData, EdgeData> | Iterable<ElementDefinition<NodeData | EdgeData>> | elements in definition, columnar or wire form, or an iterable of element definitions |
Fields of input
| Name | Description |
|---|---|
columnar: true | discriminant so the loader can tell the forms apart |
nodes: ElementDefinition<NodeData>[]? | |
edges: ElementDefinition<EdgeData>[]? | |
refs: string[] | PackedIds? | Node references (experimental with the wire format until 4.x): the
ids of nodes this payload does not carry but indexes — an edge endpoint
or a node parent |
data: DefinitionData<Data>? | |
group: GroupName? | inferred from |
position: Position? | nodes only |
collapsed: boolean? | nodes only: persisted miniature-compound state |
appliedCollapseScale: number? | nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale |
selected: boolean? | |
selectable: boolean? | |
grabbable: boolean? | |
locked: boolean? | |
pannable: boolean? | dragging this element pans the graph instead (default: true for edges, false for nodes) |
Collection<NodeData, EdgeData>a collection of the added elements
Example
const added = cy.add([ { data: { id: 'd' } }, { data: { id: 'cd', source: 'c', target: 'd' } },]);console.log(added.length); // 2if input is a collection: removed elements cannot be restored (MIGRATING.md, "Removed elements are terminally dead") — add the definitions you kept, e.g. from eles.jsons() taken before the removal