Access to all layers in the Illustrator

AiScripts
2 min readNov 9, 2021

The Adobe Illustrator CC Reference: JavaScript manual says that activeDocument.layers stores document layers. But in fact, not all, but only the top level.

There seem to be more than two layers

You can find more information in the Adobe Illustrator Scripting Guide, where you’ll find an Illustrator object model diagram. The Layer and GroupItem classes can contain nested objects of the same class, and so on.

The Illustrator Scripting Object Model

Solution

To find out the true number of layers in an Adobe Illustrator document, you need the recursive function. Example:

var counter = 0; // I know it's not good to use a global variable
countingLayers(activeDocument.layers);
alert('True layers length: ' + counter);
function countingLayers(_layers) {
for (var i = 0; i < _layers.length; i++) {
var iLayer = _layers[i];
if (iLayer.layers.length > 0) {
countingLayers(iLayer.layers);
}
counter++;
}
}

The countingLayers() function takes all top-level layers as input. In the loop we find out whether each layer contains sublayers or not. If it does, the function calls itself with a new argument: all the sublayers of the current layer.

In use

I used a similar recursion in RenameItems, to find and replace characters in layer names. Recursive functions are also good for enumerating all nested groups or getting the topmost layer where the object lies.

Rename all layers and sublayers

--

--

AiScripts

Sergey Osokin. Product Illustrator, Icon Designer, Script Developer (Ai, Ps). Writing about bugs and tricks in Adobe Illustrator scripts