I created a code to apply a random color to a path on Illustrator. However, it only applies to the first path of the layer, ignoring my selection. I know it happens because pathItems[] is 0. If it is 1, it recolorizes the second path, and so on.
How can I find out the integer number of the my current selection? So I can store it as a "AnyNumber" variable and replace docRef.pathItems[0] with docRef.pathItems[ANYNUMBER].
Reference of PathItems here.
Thank you.
var docRef = app.activeDocument;
// Create color
var rgb;
var rgb = new RGBColor();
var random1 = Math.floor((Math.random() * 255) + 1);
var random2 = Math.floor((Math.random() * 255) + 1);
var random3 = Math.floor((Math.random() * 255) + 1);
rgb.red = random1;
rgb.green = random2;
rgb.blue = random3;
// Create swatch
var swatch = docRef.swatches.add();
swatch.color = rgb;
swatch.name = "Random Color";
// Apply swatch
var pathRef = docRef.pathItems[0];
pathRef.filled = true;
pathRef.fillColor = swatch.color;
pathRef.stroked = false;
// Delete swatch
swatchToDelete = app.activeDocument.swatches[swatch.name];
swatchToDelete.remove();
I found a solution by creating an array.
Here is the whole script, if someone in the future wants to check the code:
doc = app.activeDocument;
sel = app.activeDocument.selection;
selSwatch = doc.swatches.getSelected();
if (sel instanceof Array) {
if(selSwatch.length != 0)
for (i=0; i<sel.length; i++) {
if(sel[i].typename == "PathItem" || sel[i].typename == "CompoundPathItem") {
selobj = sel[i];
selobj.filled = true;
// Create color
var rgb;
var rgb = new RGBColor();
var random1 = Math.floor((Math.random() * 255) + 1);
var random2 = Math.floor((Math.random() * 255) + 1);
var random3 = Math.floor((Math.random() * 255) + 1);
rgb.red = random1;
rgb.green = random2;
rgb.blue = random3;
// Create swatch
var swatch = doc.swatches.add();
swatch.color = rgb;
swatch.name = "Random Color";
// Apply swatch
selobj.filled = true;
selobj.stroked = false;
selobj.fillColor = swatch.color;
// Delete swatch
swatchToDelete = doc.swatches[swatch.name];
swatchToDelete.remove();
}}}