// written for // http://stackoverflow.com/questions/19302941/how-to-reference-styles-properly-in-indesign-scripting // author: @fabiantheblind // uses object ids for identification // license: wtfpl http://www.wtfpl.net
// written for
// http://stackoverflow.com/questions/19302941/how-to-reference-styles-properly-in-indesign-scripting
// author: @fabiantheblind
// license: wtfpl http://www.wtfpl.net
main();
function main(){
var doc = app.documents.add();// add a document
// create some styles
doc.paragraphStyles.add({name:"one"});
doc.paragraphStyles.add({name:"two"});
doc.paragraphStyles.add({name:"three"});
// add a group
var grp1 = doc.paragraphStyleGroups.add({name:"grp1"});
// add a style in the group
grp1.paragraphStyles.add({name:"four"});
// add a group in the group
var grp2 = grp1.paragraphStyleGroups.add({name:"grp2"});
// add a style in the group in the group
var parstylefive = grp2.paragraphStyles.add({name:"five"});
var fiveid = parstylefive.id;
var pg = doc.pages[0];// first page in new doc
var tf= pg.textFrames.add({geometricBounds:[0,0,100,100]});// add a textframe
tf.contents = TextFrameContents.PLACEHOLDER_TEXT;// add some content
var astyle = get_style(doc, fiveid);//get a style by name
if(astyle === null){
// error
alert("There is no style with that name");
}else{
// woohoo! \o/
tf.paragraphs.everyItem().appliedParagraphStyle = astyle;
}
}
/**
* This loops through all paragraph styles and returns one by his name
* could be rewritten for allCharacterStyles, allObjectStyles etc
*/
function get_style(d, id){
var thestyle = null;// result
for(var i = 0; i <d.allParagraphStyles.length;i++ ){
var onestyle = d.allParagraphStyles[i]; // isolate
if(id === onestyle.id){
thestyle = onestyle;// found it
} // end of check
} // end of loop i
// if we did not finds it we return null else Object ParagraphStyle
return thestyle;
}