Check if layer is top-level frame
Sometimes you may want to loop through your design doc, and only grab the main frames/designs.
First, this example checks if a layer is type FRAME
and either it's parent is the main page or is within a section. This will only be true for top-level frames in both instances.
code.js
// let's grab a layer node by it's ID
const layerNode = figma.getNodeById('123:456');
// prevent a figma memory leak (if not found, can't be checked)
if (layerNode !== null) {
const { type } = layerNode;
const isTopLevel = type === 'FRAME' && (parent.type === 'PAGE' || parent.type === 'SECTION');
console.log(`${layerNode.name}::isTopLevel`, isTopLevel);
}
Example usage
Let's loop through all layers in your current Figma page:
code.js
// get current page we are on in Figma
const { currentPage } = figma;
const { children } = currentPage;
const topLevelFrames = [];
children.forEach((layer) => {
const { id, name, type } = layer;
// need to specifically set the data you want
const frameData = { id, name, type };
if (type === 'FRAME') {
topLevelLayers.push(frameData);
} else if (type === 'SECTION') {
const { children: sectionChildren } = layer;
// loop through top-level section layers
sectionChildren.forEach((sectionLayer) => {
if (sectionLayer.type === 'FRAME') {
topLevelLayers.push({
id: sectionLayer.id,
name: sectionLayer.name,
type: sectionLayer.type
});
}
});
}
});