3

Мне нужно иметь возможность изменить строку текста на заголовок1 и затем выполнить некоторое дополнительное форматирование. На данный момент выучили эту часть. Вот мой пример кода на данный момент.Добавление абзаца в определенном месте

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); 
} 

Мне нужно, чтобы удалить исходную строку и добавить абзац в исходное расположение строк. Не знаете, как это сделать. любая помощь будет оценена!

ответ

7

Метод body.appendParagraph() добавляет данный абзац, как javascript, к телу, в конце его.

Вы ищете .insertParagraph (index, Paragraph). Чтобы получить индекс, попробуйте body.getChildIndex (пункт). См. Код ниже.

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); 
}; 
+0

Это возвращает ошибку «Элемент не содержит указанный дочерний элемент». Не знаете, как это сделать. – tmoney226

+0

Nevermind- Я выбирал только текст. Это прекрасно работает. Спасибо! – tmoney226

+0

Добро пожаловать! Пожалуйста, отметьте вопрос как «Ответ», чтобы другие люди могли легко найти ответ :) – filipeglfw

Смежные вопросы