NB google DOCS not google sheets.
In the following code, I believe I'm doing the following:
The end result in the document is (correctly): 'new 1 0'.
As I understand it, I can use namedRanges to encapsulate/protect text elements so that I can retrieve them and manipulate them as I want (use setText() for example, or remove()) without them being affected by or affecting any other elements in the document. That seems to be the purpose of namedRanges.
Instead of getting a namedRange '0' with one text element '0' and a namedRange '1' with one text element '1', I end up with namedRange '0' having three elements (the one I want, the text element from namedRange '1' and the independent text element 'new') and namedRange '1' having two elements (the one I want and the independent text element 'new').
What have I done wrong?
var i, j, k, element, ranges, rangeElements, rangeBuilder;
var document = DocumentApp.getActiveDocument();
var cursor = document.getCursor();
var debug = [];
for (i = 0; i < 2; i++) {
element = cursor.insertText(i + '\n');
rangeBuilder = document.newRange();
rangeBuilder.addElement(element);
document.addNamedRange(i, rangeBuilder.build());
}
cursor.insertText('new ');
for (i = 0; i < 2; i++) {
ranges = document.getNamedRanges(i);
for (j = 0; j < ranges.length; j++) {
rangeElements = ranges[j].getRange().getRangeElements();
for (k = 0; k < rangeElements.length; k++) {
debug.push(['tag: ' + i, 'element: ' + k, 'text: ' + rangeElements[k].getElement().getText()]);
}
}
}