Search code examples
javascriptadobe-indesign

How to use Javascript to delete text box by contents using itemByName in InDesign


I have an InDesign document containing data, graphs, and tables. I have text boxes that I have named "Values" that either contain data or "n/a". I would like to delete all named text boxes that do not contain the string "n/a". The following script is working to delete all text boxes that do not contain n/a, but it deletes all text boxes, including those that are not named. I've tried using doc.textFrames.itemByName("Values"), but it does not work with texts.length.

Any suggestions? Or resources that I could look at?

var doc = app.activeDocument;
var find = "n/a";
var texts = doc.textFrames;
var i = count;
var count = texts.length;

for (i = count - 1; i > 0; i--) {
    if (texts[i].contents.match(find) != find) {
        texts[i].remove();
    }
}

Solution

  • Try to change the line:

    if (texts[i].contents.match(find) != find) {
    

    with:

    if (texts[i].name == "Values" && texts[i].contents.match(find) != find) {
    

    More native and more efficient approach would be:

    var frames = app.activeDocument.textFrames.everyItem().getElements();
    
    while (f = frames.pop())
        if (f.name == "Values" && f.contents != "n/a") f.remove();
    

    To iterate through collection.everyItem().getElements() is usually much faster than through a collection.