1
votes

Following the documentation sample, I'm trying to create a function that searchs for a numerated list in a google document and, if finds it, adds a new item to that list. But I get this error: Cannot find method setListId(string). (line 21, file "test") or, if I change line 21 content (replacing elementContentfor newElement), I get the message: Preparing for execution... and nothing happens. How to fix it?

This is my code:

function test() {
  var elementContent = "New item testing"; // a paragraph with its formating
  var targetDocId = "1R2c3vo9oOOjjlDR_n5L6Tf9yb-luzt4IxpHwwZoTeLE";  
  var targetDoc = DocumentApp.openById(targetDocId);
  var body = targetDoc.getBody();
  for (var i = 0; i < targetDoc.getNumChildren(); i++) {
    var child = targetDoc.getChild(i);
    if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
        var listId = child.getListId();
        var newElement = body.appendListItem(elementContent);
        newElement.setListId(newElement);
        Logger.log("child = " + child);

    }
  }
}
1
You have created an endless loop, this message is typical of an endless loop, it will probably also return "DocumentApp service not available" so wait a bit and try to log the results without inserting new data to see what happens. (I don't have time right now to test further)Serge insas

1 Answers

2
votes

Following my comment, I tried to play with your script to see what happened and I came up with that code below...

I'm not saying it solves your issue and/or is the best way to achieve what you want but at least it gives a result that works as expected.

Please consider it as a "new playground" and keep experimenting on it to make it better ;-)

function test() {
  var elementContent = "New item testing"; // a paragraph with its formating
  var targetDocId = DocumentApp.getActiveDocument().getId();  
  var targetDoc = DocumentApp.openById(targetDocId);
  var body = targetDoc.getBody();
  var childIndex = 0;
  for (var i = 0; i < targetDoc.getNumChildren(); i++) {
    var child = targetDoc.getChild(i);
    if (child.getType() == DocumentApp.ElementType.LIST_ITEM){
      while(child.getType() == DocumentApp.ElementType.LIST_ITEM){
        child = targetDoc.getChild(i)
        childIndex = body.getChildIndex(child);
        Logger.log(childIndex)
        i++
      }
      child = targetDoc.getChild(i-2)
      var listId = child.getListId();
      Logger.log(childIndex)
      var newElement = child.getParent().insertListItem(childIndex, elementContent);
      newElement.setListId(child);
      break;
    }
  }
}

enter image description here