Google Docs API – How to Get the Position of a Paragraph

google docsgoogle-apps-script

Using GAS, I'm trying to navigate paragraphs in a google doc and record their starting position so that I can display an interactive navigation menu in a sidebar. But I can't find any GAS method that returns the position of a paragraph (or an element for that matter), except when the cursor is within that paragraph. I thought of inserting bookmarks to retrieve their positions, but it seems that one cannot insert a bookmark without having first a position…

Am I missing anything?

Note that I'm aware of the fact that headings have hash locations (except for normal paragraphs) that are easy to retrieve using a TOC; but I can't use these hash locations directly in any GAS add-on, because the caja compiler prevents it. Besides, I'd like to list more than headings in my navigation menu.

Best Answer

Use the Document.newPosition(element, offset) method, where element is your Paragraph object and offset is 0.

For example:

var newParagraph = body.appendParagraph("some text");
var paragraphPosition = doc.newPosition(newParagraph, 0);