I am trying to create a Google Apps Script that could help navigate through the headers.

I have currently a code searching the position with the function "findText" that I used in a custom menu in my Doc.

function goto (title) {
 //Get element
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();

  //Search element
  var searchType = DocumentApp.ElementType.PARAGRAPH;
  var searchResult = null;
  searchResult = body.findText(title, body.findText(title)) 
  var position = doc.newPosition(searchResult.getElement(), 1);

However, this seems to run slow on my browser so I would like to improve the speed by getting the position of the headers directly by using, for example, the information of their corresponding URLs (e.g. #heading=h.wtr4epyf5xix).

Does something like doc.newPosition(body.getHeader("wtr4epyf5xix")) would exist?

1 Answer 1


There's no way to obtain heading URLs, this is a popular but unsatisfied request. However, you can speed up your function by only looking into headings:

function goto ( title ) {
  var doc = DocumentApp.getActiveDocument (),
      body = doc.getBody (),
      searchType = DocumentApp.ElementType.PARAGRAPH,
      searchResult = null;

  while ( searchResult = body.findElement ( searchType, searchResult ) ) {
    var par = searchResult.getElement ().asParagraph (),
        heading = par.getHeading ();
    switch ( heading ) {
      case DocumentApp.ParagraphHeading.HEADING1:
      case DocumentApp.ParagraphHeading.HEADING2:
      case DocumentApp.ParagraphHeading.HEADING3:
      case DocumentApp.ParagraphHeading.HEADING4:
      case DocumentApp.ParagraphHeading.HEADING5:
      case DocumentApp.ParagraphHeading.HEADING6:
        if ( par.findText ( title ) ) { 
          // assumes that title is unique among headings
          // and it does not appear as a subset of a heading
          doc.setCursor ( doc.newPosition ( par, 1 ) );

If you want to help, you can star the corresponding Google Apps script issue.

EDIT: Fixed a]two syntax errors


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.