How to select a layer?

This might be a stupid question but once again, the API documentation wasn’t very helpful (or it was too hidden away to find). How can I select a layer (or layer group) - make it active - by its variable reference?

In CEP it was simple … docRef.activeLayer = layer1;

I tried “docRef.activeLayers[0] = layer1” or “docRef.activeLayers = [layer1]”, but that didn’t work.

1 Like

Hi @AndreasResch ,

It’s not a stupid question. The Layer’s properties aren’t listed in the documentation. I hope you found your answer before now, but just in case, here is one way using layer.selected (I found that property by printing a layer to the Console in UXP Developer Tool Debug Mode):

const ps = window.require("photoshop").app;
let doc = ps.activeDocument;
let all_layers = doc.layers;

const select_layer_by_name = (name) =>
{
  doc = ps.activeDocument;
  doc.layers.forEach(function(layer)
  {
    if (layer.name == name)
    {
      layer.selected = true;
    }
  });
}

const select_layer_by_index = (id) =>
{
  doc = ps.activeDocument;
  if (doc.layers[id] !== "undefined")
  {
    doc.layers[id].selected = true;
  }
}

select_layer_by_index(0); // selects the first layer
select_layer_by_name("Background"); //selects the layer 'Background'

Here’s another way using batchPlay:

async function select_layer_by_name2(name) {
  const result = await batchPlay(
    [{
      "_obj": "select",
      "_target": [{
        "_ref": "layer",
        "_name": name
      }],
      "makeVisible": false,
      "_isCommand": true
    }], {
      "synchronousExecution": false
    });
}

These select_layer_by_name functions don’t account for when there are multiple layers with the same name. Maybe someone else can chime in with that.

1 Like

Keep in mind that layer.selected of the DOM API currently only affects this specific layer. In most cases you want to exclusively select a layer, so you’ll have to loop all activeLayers before and make them selected = false

1 Like