how to encapsulate/protect text elements in google docs' namedRanges?

48 views
Skip to first unread message

Mark Grimshaw-Aagaard

unread,
Mar 17, 2021, 5:10:47 AM3/17/21
to Google Apps Script Community

NB google DOCS not google sheets.


In the following code, I believe I'm doing the following:

  1. Insert two text elements ('0' and '1') then encapsulate them in two namedRanges tagged respectively with the names '0' and '1'. i.e. two namedRanges each with one text element only.
  2. Insert a new text element that is not part of any namedRange.
  3. Retrieve the text of the two named ranges.

The end result in the document is (correctly): 'new 1 0'.


However, when I print out the contents of the debug array, I get:
enter image description here

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()]);
     
}
   
}
 
}


Reply all
Reply to author
Forward
0 new messages