Google Apps Script: How to find a listItem object in a google document and insert a item to it?

后端 未结 1 1534
栀梦
栀梦 2021-01-24 14:15

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

相关标签:
1条回答
  • 2021-01-24 14:41

    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

    0 讨论(0)
提交回复
热议问题