Toggle visibility for sublayers in AI

I want to toggle the visibility of the sublayers with a certain name. Now, I’ve seen it done for a layer:

#target illustrator
all_layers = app.activeDocument.layers.getByName("Layer 8")
all_layers.visible = ! all_layers.visible

Here is how I reference a sublayer, but I cannot connect the dots.

How to reference a sublayer by name in an Illustrator script?



Considering that you are working with groups (and not nested layers), the below script will toggle the “hidden” attribute of groups within layers (and nested layers):

// jshint -W118
// globals app

// jshint ignore:start
#target illustrator
#targetengine main
// jshint ignore:end

function loop(flag, layers) {

    var groups, groupsCount;
    var subLayers, subLayersCount;
    var i1, i1l;
    var i2, i2l;

    // Loop over layers:
    for (i1 = 0, i1l = layers.length; i1 < i1l; i1++) {

        $.writeln('Layer: ', layers[i1].name);

        // Get layer groups:
        groups = layers[i1].groupItems;
        groupsCount = groups.length;

        // If there are nested groups:
        if (groupsCount) {

            for (i2 = 0, i2l = groups.length; i2 < i2l; i2++) {

                $.writeln('Group: ', groups[i2].name);

                // Does group match flag?
                if (groups[i2].name.toLowerCase() == flag) {

                    // Flag matched, so toggle hidden attribute:
                    groups[i2].hidden = ( ! groups[i2].hidden);




        // Get layer layers:
        subLayers = layers[i1].layers;
        subLayersCount = layers.length;

        // If there are nested layers:
        if (subLayersCount) {

            // Call self and recurse:
            loop(flag, subLayers);




if (app.documents.length > 0) {

    // This script assumes you want to toggle visibility of “groups”
    // with a name that matches first argument passed below.
        'featured product', // Group name used to toggle visibility.


Test file:

Note that I didn’t take into account nested layers with the name of “featured product”, but (not having given this scenario too much thought) you could simply add a condition to toggle the layer visibility for that layer instead of recursing into it’s contents.

Ideas for a slight improvements to the code:

  • Prompt the user to input a string as the target group name to toggle
  • Include an option to show/hide layers in that same prompt window (as a checkbox perhaps?)
  • Wrap code in IIFE plus general house cleaning of syntax

Be warned that I have not stress-tested the above code, so caveat emptor. 🙂

Source : Link , Question Author : D.Montana , Answer Author : mhulse

Leave a Comment