Test whether a layer with a specific name exists?
Is there a simple way to test whether a layer with a specific name exists?
Is there a simple way to test whether a layer with a specific name exists?
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
Already have an account? Login
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.