Copy link to clipboard
Copied
Hi,
Could someone please help me? I need my script to create a new character style only if a style with that name doesn't already exist. What would be the best way of checking for this?
In plain(ish) English, I need something like:
if app.activeDocument.characterStyles already contains a style named "ScriptItalics" etc. etc.
Can I do this without actually looping through every item?
Thank you,
Ariel
You can also do this like so:
var myDoc = app.activeDocument;
if (myDoc.characterStyles.item("ScriptItalics") == null) {
var myCharStyle = myDoc.characterStyles.add({name:"ScriptItalics"});
}
else {
var myCharStyle = myDoc.characterStyles.item("ScriptItalics");
}
And since you are on CS4, you can use isValid property to check if an object specifier resolves to a valid object:
if (!myDoc.characterStyles.item("ScriptItalics").isValid) {
var myCharStyle = myDoc.characterStyles.add({name
...Copy link to clipboard
Copied
try { newstyle = app.activeDocument.characterStyles.add({name:"Cursief"}); } catch (e) { alert ("No Can Do."); }
Copy link to clipboard
Copied
Thanks! What I'll do then is a slight modification of Jongware's suggestion, just so that I end up with the same result whether or not the style exists, i.e.:
try { newstyle = app.activeDocument.characterStyles.add({name:"Cursief"}); } catch (e) {newstyle = app,activeDocument.characterStyles.name("Cursief")}
Of course, this stills risks crashing if the error was thrown for a different reason than the character style with that name already exists, though I can't think what that might be..
Thanks again,
Ariel
Copy link to clipboard
Copied
Yes, this is exactly what I generally do. It's difficult to imagine another error than "already exists" -- but if it does happen, well, no problem, as the script will halt on the next line (asking for a style with that name while it still does not exist).
Copy link to clipboard
Copied
you need to use try ... catch() and try to get reference to CharStyle with your name - if it doesn't exist - you will raise error and you can react to this error
but I'm not JS man so you need to search forum for example
robin
www.adobescripts.co.uk
Copy link to clipboard
Copied
You can also do this like so:
var myDoc = app.activeDocument;
if (myDoc.characterStyles.item("ScriptItalics") == null) {
var myCharStyle = myDoc.characterStyles.add({name:"ScriptItalics"});
}
else {
var myCharStyle = myDoc.characterStyles.item("ScriptItalics");
}
And since you are on CS4, you can use isValid property to check if an object specifier resolves to a valid object:
if (!myDoc.characterStyles.item("ScriptItalics").isValid) {
var myCharStyle = myDoc.characterStyles.add({name:"ScriptItalics"});
}
Copy link to clipboard
Copied
Thank you Kasyan. IsValid seems to be the most concise (haven't tried it yet though). Null is also a good idea.
Thanks,
Ariel