Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Working with a Component Body in JavaScript

These are useful and common patterns for working with a component’s body in JavaScript.

In these examples, cmp is a reference to a component in your JavaScript code. It’s usually easy to get a reference to a component in JavaScript code. Remember that the body attribute is an array of components, so you can use the JavaScript Array methods on it.

When you use cmp.set("v.body", ...) to set the component body, you must explicitly include {!v.body} in your component markup.

Note

Replace a Component's Body

To replace the current value of a component’s body with another component:

1// newCmp is a reference to another component
2cmp.set("v.body", newCmp);

Clear a Component's Body

To clear or empty the current value of a component’s body:

1cmp.set("v.body", []);

Append a Component to a Component's Body

To append a newCmp component to a component’s body:

1var body = cmp.get("v.body");
2// newCmp is a reference to another component
3body.push(newCmp);
4cmp.set("v.body", body);

Prepend a Component to a Component's Body

To prepend a newCmp component to a component’s body:

1var body = cmp.get("v.body");
2body.unshift(newCmp);
3cmp.set("v.body", body);

Remove a Component from a Component's Body

To remove an indexed entry from a component’s body:

1var body = cmp.get("v.body");
2// Index (3) is zero-based so remove the fourth component in the body
3body.splice(3, 1);
4cmp.set("v.body", body);