2 Replies Latest reply on Oct 16, 2014 10:08 AM by subieguy2

    Layer loop stops short?

    subieguy2 Level 1
      #target illustrator
      var doc = app.activeDocument;
      var allLayers = doc.layers;
      for (var i = 0; i < allLayers.length; i++) {
          allLayers[i].locked = false;
          if (allLayers[i].name == "Hypertext" || allLayers[i].name == "Taps") {
              alert("I found the " + allLayers[i].name + " layer")
          } else {
              //alert("Not the right layer")
              allLayers[i].remove();
          }
      }
      

       

      Can anyone tell me why my loop is stopping short?

      I am trying to delete ALL of the layers in the active document that are NOT named Hypertext or Taps.

      There are 28 layers in my document (including the 2 specific layers I want to keep).

      After I run the script that I wrote (see above script) it does in fact keep my two desired layers but it also doesn't delete all the other layers. I am left with 12 layers that need to be deleted still.

       

      Anyone see what I am doing wrong?

       

      Windows 7 64bit, CS4, JavaScript

        • 1. Re: Layer loop stops short?
          Larry G. Schneider Adobe Community Professional & MVP

          Run the loop in reverse.

           

          (var i = allLayers.length-1; i =>0; i--)

          • 2. Re: Re: Layer loop stops short?
            subieguy2 Level 1

            Thanks Larry! That worked out perfect. One small edit to your code was I had to change

            (var i = allLayers.length-1; i => 0; i--)
            

            to

            (var i = allLayers.length-1; i >= 0; i--)
            

             

            Final code....

            #target illustrator
            var doc = app.activeDocument;
            var allLayers = doc.layers;
            for (var i = allLayers.length-1; i>=0; i--){
                allLayers[i].locked = false;
                if (allLayers[i].name == "Hypertext" || allLayers[i].name == "Taps") {
                    //alert("I found the " + allLayers[i].name + " layer")
                } else {
                    //alert("Not the right layer")
                    allLayers[i].remove();
                }
            }
            
            

             

            Thanks again Larry!