Check/uncheck the entire checklist in Google Documents
Currently it is unknown if the checklist can be manipulated in Docs. Clark Lind suggests to replace a list item with a copy of one of them (which is in expected state – check/uncheck). We need to know the id
– see printListIds()
– of the list in order to be able to change it. And also we need to know which element is in the right state. The code used the last one.
Important. The code does not support paragraph deep copying.
Snippet
- See full code
- Leave a comment
- Create script from the snippet *See how to use scrviz for clone Apps Script project
/**
* Check/uncheck the entire checklist in the Document
*
* @param {GoogleAppsScript.Document.Document} doc A Document
* @param {string} index The checklist id
*/
function uncheckListById_(doc, id) {
const body = doc.getBody();
const lists = body.getListItems().filter((l) => l.getListId() === id);
const last = lists.splice(-1)[0];
lists.reverse().forEach((item) => {
const copy = last.copy();
copy.asListItem().setText(item.asListItem().getText());
body.insertListItem(body.getChildIndex(item), copy);
item.removeFromParent();
});
}
Run it
run.js/* global uncheckListById_ */
/**
* Run the snippet
*/
function run() {
uncheckListById_(DocumentApp.getActiveDocument(), 'kix.yy1s6bgaip7h');
}
/**
* Prints ids of lists in the current Document
*/
function printListIds() {
console.log(getListIds_(DocumentApp.getActiveDocument()));
}
/**
* Gets ids of lists in the current Document
*
* @param {globalThis.DocumentApp.Document} doc
*/
function getListIds_(doc) {
return doc
.getBody()
.getListItems()
.reduce((a, c) => {
const id = c.getListId();
if (a.indexOf(id) === -1) a.push(id);
return a;
}, []);
}
Ui triggers
triggerActions.js/**
* Creates the user menu for handy use.
*/
function onOpen() {
DocumentApp.getUi()
.createMenu('Checklists')
.addItem('Mark the list as its last item', 'run')
.addToUi();
}