To modify the script to add each “Answer” item as a new line immediately following where it was removed, rather than at the end of the document, we need to adjust the logic to insert a paragraph right after the detected list item’s position. Here’s how you can do it:
function moveAnswerItemsToNewLines() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var numChildren = body.getNumChildren();
for (var i = 0; i < numChildren; i++) {
var child = body.getChild(i);
// Check if the child element is a list item
if (child.getType() === DocumentApp.ElementType.LIST_ITEM) {
var listItem = child.asListItem();
var text = listItem.getText();
// Check if the text starts with "Answer"
if (text.startsWith("Answer")) {
// Since we are inserting immediately after, we use the current index + 1
body.insertParagraph(i + 1, text);
// Remove the original list item
body.removeChild(child);
// Adjustments to indices not necessary here since we are inserting before deleting
numChildren--; // Decrement numChildren to reflect the removed element
}
}
}
}
This script differs from the previous version by inserting a new paragraph immediately after the current list item before removing the original list item. This approach ensures that the “Answer” items are placed directly after their original locations.
To use this updated script, follow the same steps as before:
- Open your Google Doc.
- Go to Extensions > Apps Script.
- Delete any code in the script editor and paste the updated script.
- Save the script with a name.
- Run the script by clicking the play (▶️) button or selecting the function
moveAnswerItemsToNewLines
from the dropdown next to the play button and then clicking it.
Always make sure you have a backup of your document before running scripts, especially when they involve modifying document content.