word-js-docs

Create a list

Inserts a new list into the document.

This sample demonstrates how to insert and change lists.

async function insertList() {
  // This example starts a new list with the second paragraph.
  await Word.run(async (context) => {
    const paragraphs: Word.ParagraphCollection = context.document.body.paragraphs;
    paragraphs.load("$none");

    await context.sync();

    // Start new list using the second paragraph.
    const list: Word.List = paragraphs.items[1].startNewList();
    list.load("$none");

    await context.sync();

    // To add new items to the list, use Start or End on the insertLocation parameter.
    list.insertParagraph("New list item at the start of the list", "Start");
    const paragraph: Word.Paragraph = list.insertParagraph("New list item at the end of the list (set to list level 5)", "End");

    // Set up list level for the list item.
    paragraph.listItem.level = 4;

    // To add paragraphs outside the list, use Before or After.
    list.insertParagraph("New paragraph goes after (not part of the list)", "After");

    await context.sync();
  });
}

async function setup() {
  await Word.run(async (context) => {
    const body: Word.Body = context.document.body;
    body.clear();
    body.insertParagraph(
      "Themes and styles also help keep your document coordinated. When you click design and choose a new Theme, the pictures, charts, and SmartArt graphics change to match your new theme. When you apply styles, your headings change to match the new theme.",
      "Start"
    );
    body.insertParagraph(
      "Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign.",
      "Start"
    );
    body.insertParagraph(
      "Do you want to create a solution that extends the functionality of Word? You can use the Office Add-ins platform to extend Word clients running on the web, on a Windows desktop, or on a Mac.",
      "Start"
    );
    body.paragraphs
      .getLast()
      .insertText(
        "Use add-in commands to extend the Word UI and launch task panes that run JavaScript that interacts with the content in a Word document. Any code that you can run in a browser can run in a Word add-in. Add-ins that interact with content in a Word document create requests to act on Word objects and synchronize object state.",
        "Replace"
      );
  });
}

// Default helper for invoking an action and handling errors.
async function tryCatch(callback) {
  try {
    await callback();
  } catch (error) {
    // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
    console.error(error);
  }
}