Skip to main content
Participant
August 6, 2018
Answered

Finding the top level Layerset using Javascript

  • August 6, 2018
  • 3 replies
  • 1092 views

My current code is terrible, it's a Friday afternoon special:

if(layer.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

else if(layer.parent.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

else if(layer.parent.parent.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

else if(layer.parent.parent.parent.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

else if(layer.parent.parent.parent.parent.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

else if(layer.parent.parent.parent.parent.parent.parent == doc && isLayerSet) {

     //do something in this case fileNew.write('foo');

}

I did this as a proof of concept to see if the rest of the script works (which it does).

The aim of the game for layer i want to get the name of it's top level parent (i.e. the first child of the document).

I know there is an easier way of doing this however I'm still quite new at this and I'm not sure on some of the nuances of both javascript and photoshop so any help would be massively appreciated!

This topic has been closed for replies.
Correct answer Searlee

I've managed to figure out a fix:

(function getTopLayer(element) {

   if (element.parent == doc && isLayerSet) {

        //do something in this case fileNew.write('foo'); ;

        //do something in this case fileNew.write('foo'); ;

   } else {

        getTopLayer(element.parent);

  }

})(layer);

This does the trick for the case that I wanted.

3 replies

SearleeAuthorCorrect answer
Participant
August 6, 2018

I've managed to figure out a fix:

(function getTopLayer(element) {

   if (element.parent == doc && isLayerSet) {

        //do something in this case fileNew.write('foo'); ;

        //do something in this case fileNew.write('foo'); ;

   } else {

        getTopLayer(element.parent);

  }

})(layer);

This does the trick for the case that I wanted.

Kukurykus
Legend
August 6, 2018

if doc is activeDocument, then you don't have to check it. Irrespectively that will be the deepest or top layerSet then you still get name of top layerSet without checking if document is a parent for top layerSet at same time. isLayerSet is enough.

Kukurykus
Legend
August 6, 2018

(function par(v) {return v.parent.typename == 'LayerSet' ? par(v.parent) : v})(activeDocument.activeLayer)

Legend
August 6, 2018

Maybe it's better this way.

alert(get_top_layerset(activeDocument.activeLayer))

function get_top_layerset(layer)

    {

    try {

        if (layer.parent.typename == "LayerSet" && layer.parent.parent.typename == "Document") return layer.parent;

        return get_top_layerset(layer.parent);

        }

    catch (e) { return null; }

    }