Home > Enterprise >  Apps Script - Bookmark a Date Element on Google Docs
Apps Script - Bookmark a Date Element on Google Docs

Time:09-08

In general, I want to recreate the Insert>Bookmark on Google docs with a custom function upon bookmarking an element (all types of elements).

Now my issue is on bookmarking the Date element. I am getting

TypeError: Cannot read property 'getRangeElements' of null

enter image description here

My current code for bookmarking Date element was something like this


selection.getRangeElements().forEach(e => {
  const elmnt = e.getElement();
  const type = elmnt.getType();

  if( type == DocumentApp.ElementType.DATE ){
    bookmarked = doc.addBookmark( doc.newPosition(elmnt.asDate().getParent(), 1) )
  }

}); ```

CodePudding user response:

Modification points:

  • When I saw your showing script and your error message of TypeError: Cannot read property 'getRangeElements' of null, if selection is DocumentApp.getActiveDocument().getSelection(), I'm worried that you might have run the script without selecting the smart chip of Date. Please confirm this again.
  • And, in your script, ele is not declared. So, even when the error of TypeError: Cannot read property 'getRangeElements' of null was resolved, an error occurs at const type = ele.getType();.

When these points are reflected in your script, it becomes as follows.

Modified script:

When you run this script, please select the smart chip of Date and run the script. By this, the smart chip of Date is added as the bookmark.

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const selection = doc.getSelection();
  selection.getRangeElements().forEach(e => {
    const ele = e.getElement();
    const type = ele.getType();
    if (type == DocumentApp.ElementType.DATE) {
      bookmarked = doc.addBookmark(doc.newPosition(ele.asDate().getParent(), 1));
    }
  });
}

Reference:

  • Related