Illustrator scripting: Convert all top level layers to groups

Spent the past 2 hours sorting this out… and posting in hopes it helps someone else.

With work I often receive Illustrator files exported from Rhino that have the wingsuit panels I need separated into layers but not groups, which I need in order to make my life easier moving panels around. I’ve been doing this manually for years, and only recently added a mouse button script to just group what was selected. So it was “click layer, click mouse button, click layer, click mouse button…” over and over until all layers were grouped individually, and there’s usually a lot of them. Doesn’t take forever but annoying.

I wanted a script to iterate through every top level layer, and group it. Pretty simple if you are a proficient coder. I’m not. So after banging my head against it, I finally got this script working:

if (app.activeDocument.layers.length > 1) {

for (var i = 0; i < app.activeDocument.layers.length; i++) //loop through all TOP LEVEL layers

{

app.activeDocument.layers[i].hasSelectedArtwork = true; //selects all in active layer

app.executeMenuCommand('group'); //groups all selected

app.activeDocument.selection = null; //deselect

}

} else {

alert("The active document only has only 1 layer");

}

I used the Adobe Illustrator scripting guide, this post, and this post (and a few others I forgot) as reference. I’m quite sure my code is dirty and needs variables etc… but it works so meh. I’ve been automating a bunch of tasks in Photoshop too, but they are super specific so not much help to others.

Posted on May 29, 2022 and filed under Tips.