Sg2.9
Finding Items in the Document
Index RSS

Sometimes we need to find items in a document that match a number of attributes. For example, if we were to write a script that would need the user to select an item before executing it.

This is where the document.getItems(attributes) function comes into play.

Lets say, for example, that we wanted to find the first selected item and remove it:

var selectedItems = document.getItems({
	selected: true
});

if (selectedItems.length > 0) {
	var item = selectedItems[0];
	item.remove();
} else {
	Dialog.alert('Please select something first!');
}

In the example above we pass an object with the property selected: true to the document.getItems(attributes) function to find all the selected items in the document:

var selectedItems = document.getItems({
	selected: true
});

Next we check to see if any items were actually selected by checking that the length of the selectedItems array is bigger then 0:

if(selectedItems.length > 0) {

If this is the case, we get the first item in the selectedItems array and remove it:

	var item = selectedItems[0];
	item.remove();

If no items were selected, we alert the user to select one next time:

} else {
	Dialog.alert('Please select something first!');
}
Please note:

To find out more about dialogs, read the Displaying Dialog Windows tutorial.

Another example could be to find all the hidden items in a document and remove them:

var hiddenItems = document.getItems({
	hidden: true
});

// loop trough the hiddenItems array
for (var i = 0, l = hiddenItems.length; i < l; i++) {
	var item = hiddenItems[i];
	item.remove();
}

Using the document.getItems(attributes) we can also find items of a certain type.

For example, if we would want an array of all paths contained in a document:

var paths = document.getItems({
	type: Path
});

We can also match multiple types of items. To do this, we use the types property and pass it an array containing the types we want to match.

For example to match all paths and groups in the active document:

var items = document.getItems({
	types: [Group, Path]
});

We can also match multiple attributes. Lets say we want to write a script that needs the user to select a path before executing it. We would need to find all items that are both a Path and selected:

var selectedPaths = document.getItems({
	type: Path,
	selected: true
});

Selected Items Shortcut

Scriptographer also has a shortcut to find all selected items in a document, using the document.selectedItems array.

For example, lets remove all selected items in a document:

var selectedItems = document.selectedItems;
for (var i = 0; i < selectedItems.length; i++) {
	var selectedItem = selectedItems[i];
	selectedItem.remove();
}