This example demonstrates how to enable users to mutate a tree's contents, while preventing malicious XSS attacks.

{{>treeview-add-remove-source}}

The Markup

The only markup you need to create a `TreeView` is an empty container element, wrapped in the `yui3-skin-sam` class. You'll also need to include some form controls for adding and removing leaves from the tree.

```
```

The CSS

To make sure that newly added leaves are visually distinct, add a single CSS class:

``` ```

The JavaScript

Create a YUI sandbox and load the `treeview` and `escape` modules (to be used later). Then render a simple tree and expand it:

``` YUI().use('treeview', 'escape', function (Y) { var tree = new Y.TreeView({ label: "This my tree", children: [ { label: "Leaf One" }, { label: "Leaf Two" } ] }); tree.render("#mytree"); tree.expand(); ```

Create an event listener for the "Add" button. When the user clicks the button, get the value of the text field and pass it in to the tree's `add()` method to create a new leaf with a new label. Since clicking the button submits the form, call `preventDefault()` to prevent a page reload.

``` Y.one("#add").on("click", function (ev) { var text = Y.one('#label-text').get('value'); tree.add({ label: '' + Y.Escape.html(text) + '' }); ev.preventDefault(); }); ```

The label is wrapped in an HTML `` element that applies the "new" class, turning the leaf green. However, the code uses `Y.Escape.html()` to escape possibly dangerous user input. Since the default `TreeView` templates allow the label to be arbitrary HTML, it's important to keep track of the HTML you want to add versus the HTML that a user might try to inject.

Finally, create an event listener for the "Remove" button to select and remove the first element of the tree.

``` Y.one("#remove").on("click", function (ev) { if (tree.item(0)) { tree.item(0).remove(); } ev.preventDefault(); }); ```

Complete Example Source

``` {{>treeview-add-remove-source}} ```