Skip to main content
Known Participant
May 23, 2017
Answered

Check if layers exist, remove layers, or move on

  • May 23, 2017
  • 1 reply
  • 5002 views

I created a simple script to remove layers.

app.activeDocument.layers.getByName('Engineering Part Numbers').remove();

It worked fine, but if the layers don't exist, I get an error "No such element". So I built up the script to check the layer, if it exists, remove it, else give me an alert. I don't really need the alert, but I thought I'd put it in there for testing.

I've looked around and couldn't find what I need, other than Photoshop or InDesign. But they don't seem to be the same as Illustrator. I'm assuming I am either not using the if/else incorrectly, or maybe a For statement with Var to define the layer. Just not certain how to do that, and I find the documentation very lacking. Unfortunately, I started off small and kept building, now I'm so lost, I don't know where to go.

This is the start of a much larger script if you were wondering.

I am using Windows 10 and Illustrator CC2017

if (app.activeDocument.layers.getByName('Engineering Part Numbers') == true) {

app.activeDocument.layers.getByName('Engineering Part Numbers').remove();

    alert("Engineering Part Numbers is Gone");

    }    else {

        alert("No Engineering Part Numbers Layer");

    }

Thanks everyone.

This topic has been closed for replies.
Correct answer pixxxelschubser

Hi michaelk97081953​,

you can use a try/catch clause for this eg

try {

    app.activeDocument.layers.getByName('Engineering Part Numbers').remove();

    }

catch (e) {

    alert("the layer doesn't exist");

    // do whatever you want

    }

Have fun

1 reply

pixxxelschubser
Community Expert
pixxxelschubserCommunity ExpertCorrect answer
Community Expert
May 23, 2017

Hi michaelk97081953​,

you can use a try/catch clause for this eg

try {

    app.activeDocument.layers.getByName('Engineering Part Numbers').remove();

    }

catch (e) {

    alert("the layer doesn't exist");

    // do whatever you want

    }

Have fun

Known Participant
May 23, 2017

Pixxxel, that is great. I figured I was over thinking it. It works as it should. It didn't work at first and I was like, what the heck. Helps if I spell everything correctly. I placed it in my much larger script and at is well.

Thank you Pixxxel.

MichaelK ¯\_(ツ)_/¯