You can achieve this type of effect using NamedRanges. Basically, the strategy is to:
- Add your text, paragraph or other Document Elements
- Wrap that text in a Document NamedRange
- Record the NamedRange ID, and associate it with any other data you need to attach to that specific text (such as time of insertion, or custom attributes, or whatever).
- Later, when you need to find that text (or just determine if it exists), you can query your list of NamedRange IDs and then use the ID to reference the text in the doc.
Here's a rough implementation of this type of strategy:
function testing() {
// Add a new paragraph within a Named Range
var named = addTextWithNamedRange('This is my added text', 'RangeLabel01');
// NamedRanges can share the same names, but the IDs are unique,
// so use IDs to easily reference specific NamedRanges
var namedId = named.getId();
// Now save this ID to a data structure, along with any other information
// about it you need to record
// Later, when you need to reference that text/paragraph/element,
// use the ID to find it, and make any changes you need:
accessNamedRange(namedId);
}
function addTextWithNamedRange(str, name) {
// Add a new paragraph to end of doc
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.appendParagraph(str);
// Creates a NamedRange that includes the new paragraph
// Return the created Named Range
var rangeBuilder = doc.newRange();
rangeBuilder.addElement(text);
return doc.addNamedRange(name, rangeBuilder.build());
}
function accessNamedRange(rangeId) {
// Determine if a NamedRange with this ID exists
// If it does, log information about it and the Paragraph
// elements it includes
var doc = DocumentApp.getActiveDocument();
var named = doc.getNamedRangeById(rangeId);
if (named) {
var rangeElements = named.getRange().getRangeElements();
for(var r in rangeElements) {
var text = rangeElements[r].getElement().asParagraph().getText();
// Just logging here, but could potentially edit or
// otherwise manipulate the text
Logger.log('Found NamedRange ' + named.getName() +
' (id='+rangeId+') --> ' + text);
}
}
}