Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Group all Objects on a document in Illustrator CC with Javascript?

How to Group all Objects on a document in Illustrator CC with Javascript? I try to make a script and I need to group all the objects in the document without errors and correctly. In the official guideline I did not find such a function. The code below does not correctly group objects. Objects change places and move to the foreground or to the background. Who can help me?

function group(){     
    var docRef = app.activeDocument;
    var layerRef = docRef.layers[0];

    layerRef.hasSelectedArtwork=true;
    docSelection = app.activeDocument.selection;
    newGroup = app.activeDocument.groupItems.add();
    for ( i = 0; i < docSelection.length; i++ ) {
        newItem = docSelection[i];
        newItem.moveToBeginning( newGroup );
    }
}
like image 644
Max_Pro Avatar asked Oct 22 '25 16:10

Max_Pro


1 Answers

I tried to do the same thing with your code and get everything reversed. The problem is in your loop you take the element [i] and move it to the group, so the selection array doesn't has the same length and the loop from 0 to length is no more valid. I tried a loop on the selection array from 0 to length, but just moving the last selection element each time :

layer.hasSelectedArtwork = true;
var selection = activeDocument.selection;
var groupItem = layer.groupItems.add();
var count = selection.length;
for(var i = 0; i < count; i++) {
    var item = selection[selection.length - 1];
    item.moveToBeginning(groupItem);
}

For me, it works. I hope it can help you.

like image 125
superrache Avatar answered Oct 25 '25 05:10

superrache