Skip to main content
Participating Frequently
May 3, 2023
Question

Finding specific groups by name

  • May 3, 2023
  • 1 reply
  • 512 views

Hi all,

Working on a script to handle anchored groups. But I only want to target specific anchored groups by their name.
I have managed it to work for before when I wanted to target a rectangle within a group:

var t = myDoc.stories.everyItem(0).groups.everyItem(0).rectangles.item("image").getElements();
t.length returns the correct number of groups with a rectangle inside with the name "image. And I can use t to select the rectangle.
But whe I try to do it with the groups instead:
var t = myDoc.stories.everyItem().groups.item("marginImage").getElements();
t.length only return "1" even tif there are several groups it the name "marginImage".
Can anyone figure out why it's not working for the groups?
My best regards!
This topic has been closed for replies.

1 reply

brian_p_dts
Community Expert
Community Expert
May 3, 2023

groups.item or itemByName will only return the first element of a given name found in its parent everyItem element. Because there I assume there is only one "image" in every story>>group, then it returns correct.  

var t = app.activeDocument.stories.everyItem().groups.everyItem().rectangles.item("image").getElements();

 However, if you just have one story, then you are only getting the first marginImage group found in that story. 
To get around that, you can collect all the items in an array using myDoc.allPageItems and operate that way: 

var allMarginGroups = [];
var apis = myDoc.allPageItems;
var i = apis.length;
while(i--) { 
     if (apis[i].name == "marginImage" && apis[i].constructor.name == "Group") {
         allMarginGroups.push(apis[i]);
     }
}
Participating Frequently
May 3, 2023

©brainp311
Thank you for your quick reply. In the first example there are many groups within one story and some of them have a rectangle with the name "image". That count ends up correct.
But the problem is that I triy the same "logic" directly on a group and that's wy it isn't working?

brian_p_dts
Community Expert
Community Expert
May 3, 2023

Break it down like this: stories.everyItem().groups.everyItem() ---- 

Within every group, there is one rectangles.itemByName("image")

Thus, your count is correct, because one image itemByName is being found within each group. 

But, consider stories.everyItem() --- 

Assuming there is just one story, the groups.itemByName("marginImage") is finding just the first group in the single story. If you had multiple stories with just one marginImage group in each story, then your count would show correct. 

"item" or "itemByName" finds only the first instance of the object in its parent; ie., if I just searched for myDoc.groups.itemByNaeme("marginImage"), I would only find one, even if my document contained multiple unanchored groups called marginImage

This is why using allPageItems is the correct use case in your scenario.