• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers
Exit
0

Test whether a layer with a specific name exists?

Engaged ,
Dec 27, 2010 Dec 27, 2010

Copy link to clipboard

Copied

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

TOPICS
Scripting

Views

7.9K

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 2 Correct answers

Community Expert , Dec 28, 2010 Dec 28, 2010

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

}

Votes

Translate

Translate
Enthusiast , May 12, 2023 May 12, 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 = func
...

Votes

Translate

Translate
Community Expert ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

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

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guru ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

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

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

I was afraid of that...

So place it inside a try-catch clause. If you arrive to the catch part, then

you know the layer doesn't exist.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guru ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

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?

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

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

}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Guru ,
Dec 28, 2010 Dec 28, 2010

Copy link to clipboard

Copied

That is what I do now… I just thought I may have overlooked a better method. For me getByName() should return 'null' like you first suggested… using item() in indesign does not error it returns a layer object but it does error when I try access any properties… It does getAbitConfusing() Thanks any how… I do wish this app had those everyItem() things too… They are most helpful…

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
Mar 11, 2014 Mar 11, 2014

Copy link to clipboard

Copied

Hi Gilad D,

Not exit with Multiple layer names, working only for one layer name, can you help me for this, how to get multiple names.

function doesLayerExist(layers, name) {

    for (i=0; i<layers.length; i++) {

        if (layers.name==name) return true;

    }

    return false;

}

//Exit script with finding layer names

if (doesLayerExist(app.activeDocument.layers, "Background", "Artwork", "diecut", "size", "sign of panel")) {

var docRef = app.activeDocument;

with (docRef) {

var docName = baseName(name);

var pdfOptions = new PDFSaveOptions();

pdfOptions.pDFPreset = '[High Quality Print]';

var saveAsPath = new File('~/Desktop/Watched Folder/Out/' + docName + '.pdf')

saveAs(saveAsPath, pdfOptions);

}

// do something if the layer exists

} else {

alert ("Document contains Specified Layer Name");

}

Thanks in advance

simon

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Mentor ,
Mar 11, 2014 Mar 11, 2014

Copy link to clipboard

Copied

Simon Dav wrote:

- Multiple layer names

- working only for one layer name

- can you help me for this, how to get multiple names.

- layers "Background", "Artwork", "diecut", "size", "sign of panel"

This should work, as one possible approach:

var doc = app.activeDocument

var layersToTargetNameArray = ["Background", "Artwork", "diecut", "size", "sign of panel"];

for (var i = 0, il = doc.layers.length; i < il; i++) {

    var curLayer = doc.layers;

    for (var j = 0, jl = layersToTargetNameArray.length; j < jl; j++) {

        if (curLayer.name == layersToTargetNameArray) {

            // --------------------------------------------

            // do something if layer name found

            // --------------------------------------------

            curLayer.visible = false; // basic example

        } else {

            // --------------------------------------------

            // do something else if layer name not found

            // --------------------------------------------

        }

    }

}

Hope it helps your efforts.

Please Note: If your question exceeds this working response with further unrelated requirements (non related to this thread) you should start a new thread instead for your question, as proper etiquette.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Mar 03, 2019 Mar 03, 2019

Copy link to clipboard

Copied

hi, how can i use regex in the search for the layer name? basically i need to search for a layer name using regex and do something... I tried changing the name, adding a var re = \Layer1\i, changing the "Layer1" to \Layer1\ig in the if statement... etc. nothing works...

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

}

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Mar 03, 2019 Mar 03, 2019

Copy link to clipboard

Copied

Try this:

if (new RegExp(name).test(layers.name)) return true;

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Mar 03, 2019 Mar 03, 2019

Copy link to clipboard

Copied

Couldn't stop thinking about ti for 2 weeks. You made my day!

Thank you so much!

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
New Here ,
May 12, 2023 May 12, 2023

Copy link to clipboard

Copied

when you iterating through the layers it should be

 

if (layers[i].name==name) return true;

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Explorer ,
Dec 31, 2010 Dec 31, 2010

Copy link to clipboard

Copied

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.

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Enthusiast ,
May 12, 2023 May 12, 2023

Copy link to clipboard

Copied

LATEST

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

 

 

Votes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines