Expand and Collapse Nodes

Expand a Node Initially

If a node is supposed to be expanded initially, set its expanded field to true. This is a conventional field name defined by the Default Item Template pattern. If another field specifies whether a node is expanded or collapsed, assign its name to the expandedExpr option as shown in the following code.

JavaScript
var hierarchicalData = [{
    name: 'Fruits',
    isExpanded: true,
    items: [
        { name: 'Apples' },
        { name: 'Oranges' }
    ]
}, {
    name: 'Vegetables',
    isExpanded: true,
    items: [
        { name: 'Cucumbers' },
        { name: 'Tomatoes' }
    ]
}];

$(function() {
    $("#treeViewContainer").dxTreeView({
        dataSource: hierarchicalData,
        keyExpr: 'name',
        displayExpr: 'name',
        expandedExpr: 'isExpanded'
    });
});

Expand/Collapse Nodes in Code

To expand or collapse a node in code, call the expandItem(itemElement) or collapseItem(itemElement) method passing the key of the node as a parameter.

JavaScript
$("#treeViewContainer").dxTreeView("expandItem", nodeKey);
// $("#treeViewContainer").dxTreeView("collapseItem", nodeKey);

Expand/Collapse Events

When a node is being expanded or collapsed, the TreeView fires the itemExpanded or itemCollapsed event. You can subscribe to them when configuring the widget using the onItemExpanded or onItemCollapsed options, or afterwards using the on() method. For more details, see the Handle Events article.

JavaScript
$(function() {
    $("#treeViewContainer").dxTreeView({
        // ...
        // Subscribing to the events when configuring the widget
        onItemExpanded: function (e) { ... },
        onItemCollapsed: function (e) { ... }
    });

    // Subscribing to the events after the widget is configured
    $("#treeViewContainer").dxTreeView("instance").on({
        "itemExpanded": function (e) { ... },
        "itemCollapsed": function (e) { ... }
    });
});
See Also