Adding a paragraph at a specific location

I need to be able to change the line of text in header1 and do some additional formatting later. At the moment we have learned this part. Here is my sample code for now.

function pocket() {
    // Try to get the current selection in the document. If this fails (e.g.,
    // because nothing is selected), show an alert and exit the function.
    var selection = DocumentApp.getActiveDocument().getSelection();
    var body = DocumentApp.getActiveDocument().getBody();
    if (!selection) {
        DocumentApp.getUi().alert('Cannot find a selection in the document.');
        return;
    }
    var selectedElements = selection.getSelectedElements();
    var selectedElement = selectedElements[0];
    var pocketelement = selectedElement.getElement().getText();
    body.appendParagraph(pocketelement).setHeading(DocumentApp.ParagraphHeading.HEADING1);
}

      

I need to remove the original line and add a paragraph at the original position of the lines. Not sure how to do it. any help would be appreciated!

+3


source to share


1 answer


The body.appendParagraph () method appends the given paragraph, for example javascript, to the body at the end of it.

You're looking for .insertParagraph (index, Paragraph). To get the index try body.getChildIndex (item). See code below.



function pocket() {
  // Try to get the current selection in the document. If this fails (e.g.,
  // because nothing is selected), show an alert and exit the function.
  var doc = DocumentApp.getActiveDocument();
  var selection = doc.getSelection();
  var body = doc.getBody();
  if (!selection) {
      DocumentApp.getUi().alert('Cannot find a selection in the document.');
      return;
  }
  var selectedElements = selection.getSelectedElements();
  var selectedElement = selectedElements[0];
  //holds the paragraph
  var paragraph = selectedElement.getElement();
  //get the index of the paragraph in the body
  var paragraphIndex = body.getChildIndex(paragraph);
  //remove the paragraph from the document
  //to use the insertParagraph() method the paragraph to be inserted must be detached from the doc
  paragraph.removeFromParent();
  body.insertParagraph(paragraphIndex, paragraph).setHeading(DocumentApp.ParagraphHeading.HEADING1);
};

      

+7


source







All Articles