Fnykis
7/4/2017 - 3:34 AM

Find a layer from name and type

Find a layer from name and type

/*
  FUNCTION DESCRIPTION:
    Will find a layer by looking for name and type
    
  INPUT:
    nameInput (String) = The name of the layer you're looking for
    type (String) = "ArtLayer" or "LayerSet" or "Any"
    
  OUTPUT:
    Returns the matching layer as an object
    If multiple layers were found - returns an array of those layers
    Returns Null if no layer was found
    
  NOTE:
    None
*/

function findLayer(nameInput,type) {
	
	function diveDeeper(layerInput) {
		
		if (type == "Any") {
			// Finding both ArtLayers and LayerSets
			if (layerInput.name == nameInput) results.push(layerInput);
		} else {
			// Finding layers with specified type
			if (layerInput.name == nameInput && layerInput.typename == type) results.push(layerInput);
		}
		
		if (layerInput.typename === "LayerSet"){
			if (layerInput.layers.length > 0){
				// When finding a layerset - dive deeper into the ocean
				for (var i = layerInput.layers.length-1; i > -1; i--) diveDeeper(layerInput.layers[i]);
			}
		}
		
	}
	
	var input = activeDocument.layers[0]; // Starting at the top layer to explore the entire document
	var results = []; // Will be filled with results
	
	diveDeeper(input);
	
	if (!results.length) return null;
	if (results.length == 1) return results[0];
	if (results.length > 1) return results;
	
}