I try to create a very simple script that adds one page after every existing page of the document and applies one of the masters to it.

Unfortunately I have a problem with referencing objects in Extend Script.

var docRef = app.activeDocument;
var numOfPages = docRef.pages.count();

for (currentPageNumber = 1; currentPageNumber <= numOfPages; currentPageNumber += 2) {
    var pageRef = docRef.pages.item[currentPageNumber];
    pageRef = docRef.pages.add(LocationOptions.AFTER, pageRef);
    docRef.pages[currentPageNumber + 1].appliedMaster = docRef.pages.masterSpreads.item ('T-test');

Can anyone help me understand where I've missed something to get this running?

1 Answer 1


There are two issues with your script. First, as you mentioned, the referencing is not quite correct.

The item property of a collection is not an array, so you cannot address it as such. Instead you can use the pages collection itself like an array. So your line

var pageRef = docRef.pages.item[currentPageNumber];

should be changed to

var pageRef = docRef.pages[currentPageNumber];

Note that this collection is zero-based, so your loop should start at zero.

Also, masterSpreads is not a property of pages, but of the doc itself, so the last line needs to be changed to

docRef.pages[currentPageNumber + 1].appliedMaster = docRef.masterSpreads.item ('T-test');

Lastly, your loop as it is now will mess up the page indices, as you keep adding new pages. Let's say your document has 8 pages in the beginning, then you would need to end up with 16 pages in the end. However, the loop ends after it reachers numOfPages (8) and thus will only add half the pages. You therefore have to loop backwards and start adding a page behind the last page, then one behind the page before that and so on. So your loop will have to look like this:

for (var i = numOfPages - 1; i >= 0; i--) {
  $.writeln("i: " + i);
  var pageRef = docRef.pages[i];
  pageRef = docRef.pages.add(LocationOptions.AFTER, pageRef);
  docRef.pages[i + 1].appliedMaster = docRef.masterSpreads.item('T-Test');

This way it should work.

  • 1
    Indeed, now it works perfectly. Thank you very much for your help. I should invest more time in investigating the reference...
    – LMPogoda
    Commented Jun 26, 2019 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.