Skip to main content
Inspiring
December 27, 2010
Answered

Test whether a layer with a specific name exists?

  • December 27, 2010
  • 3 replies
  • 9782 views

Is there a simple way to test whether a layer with a specific name exists?

This topic has been closed for replies.
Correct answer Inventsable

Since this post is being necro'd and we never know when people will come across this on Google in future, the solutions in this thread will only work for top-level layers. If you have layers within layers and any nesting then they no longer work and Layers.getByName tends to cause silent failure for me often, so a recursive solution that handles any depth (and can be pretty easily modified to be any attribute beyond name) could be:

 

function findLayerByName(name) {
    Array.prototype.find = function (callback) {
        for (var i = 0; i < this.length; i++)
            if (callback(this[i], i, this)) return this[i];
        return null;
    };
    function get(type, parent, deep) {
        if (arguments.length == 1 || !parent) {
            parent = app.activeDocument;
            deep = true;
        }
        var result = [];
        if (!parent[type]) return [];
        for (var i = 0; i < parent[type].length; i++) {
            result.push(parent[type][i]);
            if (parent[type][i][type] && deep)
                result = [].concat(result, get(type, parent[type][i], deep));
        }
        return result;
    }
    return get("layers").find(function (layer) {
        return layer.name == name; // Any true expression here safely returns our target layer
    });
}

var deeplyNestedLayer = findLayerByName("5 depths down");
var doesntExist = findLayerByName("foobar"); 
alert(deeplyNestedLayer); // [Layer 5 depths down]
alert(doesntExist); // null

// getByName doesn't even handle nesting itself:
var failure = app.activeDocument.layers.getByName("5 depths down") // Causes script failure
alert(failure) // This alert never shows unless as try/catch

 

 

3 replies

Inventsable
InventsableCorrect answer
Legend
May 13, 2023

Since this post is being necro'd and we never know when people will come across this on Google in future, the solutions in this thread will only work for top-level layers. If you have layers within layers and any nesting then they no longer work and Layers.getByName tends to cause silent failure for me often, so a recursive solution that handles any depth (and can be pretty easily modified to be any attribute beyond name) could be:

 

function findLayerByName(name) {
    Array.prototype.find = function (callback) {
        for (var i = 0; i < this.length; i++)
            if (callback(this[i], i, this)) return this[i];
        return null;
    };
    function get(type, parent, deep) {
        if (arguments.length == 1 || !parent) {
            parent = app.activeDocument;
            deep = true;
        }
        var result = [];
        if (!parent[type]) return [];
        for (var i = 0; i < parent[type].length; i++) {
            result.push(parent[type][i]);
            if (parent[type][i][type] && deep)
                result = [].concat(result, get(type, parent[type][i], deep));
        }
        return result;
    }
    return get("layers").find(function (layer) {
        return layer.name == name; // Any true expression here safely returns our target layer
    });
}

var deeplyNestedLayer = findLayerByName("5 depths down");
var doesntExist = findLayerByName("foobar"); 
alert(deeplyNestedLayer); // [Layer 5 depths down]
alert(doesntExist); // null

// getByName doesn't even handle nesting itself:
var failure = app.activeDocument.layers.getByName("5 depths down") // Causes script failure
alert(failure) // This alert never shows unless as try/catch

 

 

Inspiring
January 1, 2011

I wrote this function which worked for me:

    function findOrCreateLayer(layerName) {
        try { var myLayer = app.activeDocument.layers.getByName(layerName) }
        catch (err) {
            myLayer = app.activeDocument.layers.add();
            myLayer.name = layerName;
         }
        finally {
            return myLayer;
         }
    }

This works to get a layer:

    var myColorLayer = findOrCreateLayer("Color") ;

If the layer does not exist, it creates a layer with "layerName" as its name.

try67
Community Expert
Community Expert
December 28, 2010

Use the Layers getByName() method. It will return null if the layer is not found.

Inspiring
December 28, 2010

I wish this did… Either that or I am still doing this wrong… for me I get a run time error 'No such Element'

try67
Community Expert
Community Expert
December 28, 2010

I have tried that too and don't end up at the catch… Just stalls at the same point. getByName() appears fine if you 'know' of its existence before hand but is not any use to perform a test?


You can loop through the array of all the layers, checking if the name  you're looking for is in there.
You can even place it in a function that returns a boolean, like so:

function doesLayerExist(layers, name) {
    for (i=0; i<layers.length; i++) {
        if (layers.name==name) return true;
    }
    return false;
}

You can then call it like so:

if (doesLayerExist(app.activeDocument.layers, "Layer1")) {

// do something if the layer exists

} else {

// do something if the layer doesn't exists

}