简体   繁体   中英

How do I Iterate over all elements in a google document?

I'm trying to iterate over every element in the document, acquiring the start/end positions of each paragraph. But it keeps return -1. Any ideas what I'm doing wrong?

  var body = doc.getBody(); 

  var elements = body.getNumChildren();
  for( var i=0;i<elements;i++) {

   var element = body.getChild(i).copy();            
   var type = element.getType();
   if( type == DocumentApp.ElementType.PARAGRAPH ){
     var text = element.asParagraph().getText();

     var range = element.asParagraph().findElement(DocumentApp.ElementType.PARAGRAPH);
     var start = range.getStartOffset();
     var finish = range.getEndOffsetInclusive();

According to the official docs , the Range class is only accessible if there is a selection by the current user on the page. So, you can get the script to work, but it requires some user input rather than running on a blank document.

function getRange() {
  var ui = DocumentApp.getUi();

  // Get the user selection. Display an alert if there is none.
  var selection = DocumentApp.getActiveDocument().getSelection();

  if(selection) {

  // Get all the elements in the current selection
  var elements = selection.getRangeElements();

  for( var i=0;i<elements.length;i++) {

   var el = elements[i]

   // Can it be edited as text? If not, skip it
   if(el.getElement().editAsText) {
     var start = el.getStartOffset()
     var finish = el.getEndOffsetInclusive();
     ui.alert("start: " + start + ", finish: " + finish)
   } else {
      ui.alert("Text not selected!");
    }
  }
  } else {
    ui.alert("Nothing is selected!");
  }
}

The offsets check the position of the selection against the last element. If it is text, then it will return the index. If not (such as a page break or image) it will return -1.

Adding a simple onOpen event will allow you to run the script from a custom menu for testing:

function onOpen() {
  var ui = DocumentApp.getUi();

  ui.createMenu("Offsets").addItem("Run", "getRange").addToUi()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM