Word.Body class

Represents the body of a document or a section.

Extends

Remarks

[ API set: WordApi 1.1 ]

Properties

contentControls

Gets the collection of rich text content control objects in the body. Read-only.

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

endnotes

Gets the collection of endnotes in the body. Read-only.

fields

Gets the collection of field objects in the body. Read-only.

font

Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only.

footnotes

Gets the collection of footnotes in the body. Read-only.

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only.

lists

Gets the collection of list objects in the body. Read-only.

paragraphs

Gets the collection of paragraph objects in the body. Read-only. Important: Paragraphs in tables are not returned for requirement sets 1.1 and 1.2. From requirement set 1.3, paragraphs in tables are also returned.

parentBody

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws an error if there isn't a parent body. Read-only.

parentBodyOrNullObject

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only.

parentContentControl

Gets the content control that contains the body. Throws an error if there isn't a parent content control. Read-only.

parentContentControlOrNullObject

Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only.

parentSection

Gets the parent section of the body. Throws an error if there isn't a parent section. Read-only.

parentSectionOrNullObject

Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only.

style

Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property.

styleBuiltIn

Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property.

tables

Gets the collection of table objects in the body. Read-only.

text

Gets the text of the body. Use the insertText method to insert text. Read-only.

type

Gets the type of the body. The type can be 'MainDoc', 'Section', 'Header', 'Footer', or 'TableCell'. Read-only.

Methods

clear()

Clears the contents of the body object. The user can perform the undo operation on the cleared content.

getComments()

Gets comments associated with the body.

getHtml()

Gets an HTML representation of the body object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use Body.getOoxml() and convert the returned XML to HTML.

getOoxml()

Gets the OOXML (Office Open XML) representation of the body object.

getRange(rangeLocation)

Gets the whole body, or the starting or ending point of the body, as a range.

getRange(rangeLocationString)

Gets the whole body, or the starting or ending point of the body, as a range.

getReviewedText(changeTrackingVersion)

Gets reviewed text based on ChangeTrackingVersion selection.

getReviewedText(changeTrackingVersionString)

Gets reviewed text based on ChangeTrackingVersion selection.

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document.

insertBreak(breakTypeString, insertLocation)

Inserts a break at the specified location in the main document.

insertContentControl()

Wraps the body object with a Rich Text content control.

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the body at the specified location.

insertFileFromBase64(base64File, insertLocationString)

Inserts a document into the body at the specified location.

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

insertHtml(html, insertLocationString)

Inserts HTML at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocationString)

Inserts a picture into the body at the specified location.

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

insertOoxml(ooxml, insertLocationString)

Inserts OOXML at the specified location.

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText, insertLocationString)

Inserts a paragraph at the specified location.

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns.

insertTable(rowCount, columnCount, insertLocationString, values)

Inserts a table with the specified number of rows and columns.

insertText(text, insertLocation)

Inserts text into the body at the specified location.

insertText(text, insertLocationString)

Inserts text into the body at the specified location.

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

search(searchText, searchOptions)

Performs a search with the specified SearchOptions on the scope of the body object. The search results are a collection of range objects.

select(selectionMode)

Selects the body and navigates the Word UI to it.

select(selectionModeString)

Selects the body and navigates the Word UI to it.

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Word.Body object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.BodyData) that contains shallow copies of any loaded child properties from the original object.

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

untrack()

Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call context.sync() before the memory release takes effect.

Property Details

contentControls

Gets the collection of rich text content control objects in the body. Read-only.

readonly contentControls: Word.ContentControlCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

context

The request context associated with the object. This connects the add-in's process to the Office host application's process.

context: RequestContext;

Property Value

endnotes

Gets the collection of endnotes in the body. Read-only.

readonly endnotes: Word.NoteItemCollection;

Property Value

Remarks

[ API set: WordApiOnline 1.1 ]

fields

Note

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Gets the collection of field objects in the body. Read-only.

readonly fields: Word.FieldCollection;

Property Value

Remarks

[ API set: WordApiOnline BETA (PREVIEW ONLY) ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/manage-fields.yaml
// Gets all fields in the document body.
await Word.run(async (context) => {
  const fields = context.document.body.fields.load("items");

  await context.sync();

  if (fields.items.length === 0) {
    console.log("No fields in this document.");
  } else {
    for (let i = 0; i < fields.items.length; i++) {
      console.log(`Field ${i + 1}'s code: ${fields.items[i].code}`);
      console.log(`Field ${i + 1}'s result: ${fields.items[i].result}`);
    }
  }
});

font

Gets the text format of the body. Use this to get and set font name, size, color and other properties. Read-only.

readonly font: Word.Font;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Examples

// Get the style and the font size, font name, and font color properties on the body object.
// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to load font and style information for the document body.
    body.load('font/size, font/name, font/color, style');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    
    // Show the results of the load method.
    // Here we show the property values on the body object.
    const results = 'Font size: ' + body.font.size +
                    '; Font name: ' + body.font.name +
                    '; Font color: ' + body.font.color +
                    '; Body style: ' + body.style;

    console.log(results);
});

footnotes

Gets the collection of footnotes in the body. Read-only.

readonly footnotes: Word.NoteItemCollection;

Property Value

Remarks

[ API set: WordApiOnline 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Get the footnotes in the document body.
await Word.run(async (context) => {
  const footnotes = context.document.body.footnotes;
  footnotes.load("length");
  await context.sync();

  console.log("Number of footnotes in the document body: " + footnotes.items.length);
});

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection does not include floating images. Read-only.

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

lists

Gets the collection of list objects in the body. Read-only.

readonly lists: Word.ListCollection;

Property Value

Remarks

[ API set: WordApi 1.3 ]

paragraphs

Gets the collection of paragraph objects in the body. Read-only. Important: Paragraphs in tables are not returned for requirement sets 1.1 and 1.2. From requirement set 1.3, paragraphs in tables are also returned.

readonly paragraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-word-count.yaml
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  let text = [];
  paragraphs.items.forEach((item) => {
    let paragraph = item.text.trim();
    if (paragraph) {
      paragraph.split(" ").forEach((term) => {
        let currentTerm = term.trim();
        if (currentTerm) {
          text.push(currentTerm);
        }
      });
    }
  });

  let makeTextDistinct = new Set(text);
  let distinctText = Array.from(makeTextDistinct);
  let allSearchResults = [];

  for (let i = 0; i < distinctText.length; i++) {
    let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
    results.load("text");

    // Map search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display counts.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

    console.log("Search term: " + result.searchTerm + " => Count: " + length);
  });
});

parentBody

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws an error if there isn't a parent body. Read-only.

readonly parentBody: Word.Body;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentBodyOrNullObject

Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only.

readonly parentBodyOrNullObject: Word.Body;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentContentControl

Gets the content control that contains the body. Throws an error if there isn't a parent content control. Read-only.

readonly parentContentControl: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.1 ]

parentContentControlOrNullObject

Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only.

readonly parentContentControlOrNullObject: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentSection

Gets the parent section of the body. Throws an error if there isn't a parent section. Read-only.

readonly parentSection: Word.Section;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentSectionOrNullObject

Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only.

readonly parentSectionOrNullObject: Word.Section;

Property Value

Remarks

[ API set: WordApi 1.3 ]

style

Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property.

style: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

styleBuiltIn

Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property.

styleBuiltIn: Word.Style | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6";

Property Value

Word.Style | "Other" | "Normal" | "Heading1" | "Heading2" | "Heading3" | "Heading4" | "Heading5" | "Heading6" | "Heading7" | "Heading8" | "Heading9" | "Toc1" | "Toc2" | "Toc3" | "Toc4" | "Toc5" | "Toc6" | "Toc7" | "Toc8" | "Toc9" | "FootnoteText" | "Header" | "Footer" | "Caption" | "FootnoteReference" | "EndnoteReference" | "EndnoteText" | "Title" | "Subtitle" | "Hyperlink" | "Strong" | "Emphasis" | "NoSpacing" | "ListParagraph" | "Quote" | "IntenseQuote" | "SubtleEmphasis" | "IntenseEmphasis" | "SubtleReference" | "IntenseReference" | "BookTitle" | "Bibliography" | "TocHeading" | "TableGrid" | "PlainTable1" | "PlainTable2" | "PlainTable3" | "PlainTable4" | "PlainTable5" | "TableGridLight" | "GridTable1Light" | "GridTable1Light_Accent1" | "GridTable1Light_Accent2" | "GridTable1Light_Accent3" | "GridTable1Light_Accent4" | "GridTable1Light_Accent5" | "GridTable1Light_Accent6" | "GridTable2" | "GridTable2_Accent1" | "GridTable2_Accent2" | "GridTable2_Accent3" | "GridTable2_Accent4" | "GridTable2_Accent5" | "GridTable2_Accent6" | "GridTable3" | "GridTable3_Accent1" | "GridTable3_Accent2" | "GridTable3_Accent3" | "GridTable3_Accent4" | "GridTable3_Accent5" | "GridTable3_Accent6" | "GridTable4" | "GridTable4_Accent1" | "GridTable4_Accent2" | "GridTable4_Accent3" | "GridTable4_Accent4" | "GridTable4_Accent5" | "GridTable4_Accent6" | "GridTable5Dark" | "GridTable5Dark_Accent1" | "GridTable5Dark_Accent2" | "GridTable5Dark_Accent3" | "GridTable5Dark_Accent4" | "GridTable5Dark_Accent5" | "GridTable5Dark_Accent6" | "GridTable6Colorful" | "GridTable6Colorful_Accent1" | "GridTable6Colorful_Accent2" | "GridTable6Colorful_Accent3" | "GridTable6Colorful_Accent4" | "GridTable6Colorful_Accent5" | "GridTable6Colorful_Accent6" | "GridTable7Colorful" | "GridTable7Colorful_Accent1" | "GridTable7Colorful_Accent2" | "GridTable7Colorful_Accent3" | "GridTable7Colorful_Accent4" | "GridTable7Colorful_Accent5" | "GridTable7Colorful_Accent6" | "ListTable1Light" | "ListTable1Light_Accent1" | "ListTable1Light_Accent2" | "ListTable1Light_Accent3" | "ListTable1Light_Accent4" | "ListTable1Light_Accent5" | "ListTable1Light_Accent6" | "ListTable2" | "ListTable2_Accent1" | "ListTable2_Accent2" | "ListTable2_Accent3" | "ListTable2_Accent4" | "ListTable2_Accent5" | "ListTable2_Accent6" | "ListTable3" | "ListTable3_Accent1" | "ListTable3_Accent2" | "ListTable3_Accent3" | "ListTable3_Accent4" | "ListTable3_Accent5" | "ListTable3_Accent6" | "ListTable4" | "ListTable4_Accent1" | "ListTable4_Accent2" | "ListTable4_Accent3" | "ListTable4_Accent4" | "ListTable4_Accent5" | "ListTable4_Accent6" | "ListTable5Dark" | "ListTable5Dark_Accent1" | "ListTable5Dark_Accent2" | "ListTable5Dark_Accent3" | "ListTable5Dark_Accent4" | "ListTable5Dark_Accent5" | "ListTable5Dark_Accent6" | "ListTable6Colorful" | "ListTable6Colorful_Accent1" | "ListTable6Colorful_Accent2" | "ListTable6Colorful_Accent3" | "ListTable6Colorful_Accent4" | "ListTable6Colorful_Accent5" | "ListTable6Colorful_Accent6" | "ListTable7Colorful" | "ListTable7Colorful_Accent1" | "ListTable7Colorful_Accent2" | "ListTable7Colorful_Accent3" | "ListTable7Colorful_Accent4" | "ListTable7Colorful_Accent5" | "ListTable7Colorful_Accent6"

Remarks

[ API set: WordApi 1.3 ]

tables

Gets the collection of table objects in the body. Read-only.

readonly tables: Word.TableCollection;

Property Value

Remarks

[ API set: WordApi 1.3 ]

text

Gets the text of the body. Use the insertText method to insert text. Read-only.

readonly text: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Examples

// Get the text property on the body object
// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to load the text in document body.
    body.load('text');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log("Body contents: " + body.text);
});

type

Gets the type of the body. The type can be 'MainDoc', 'Section', 'Header', 'Footer', or 'TableCell'. Read-only.

readonly type: Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem";

Property Value

Word.BodyType | "Unknown" | "MainDoc" | "Section" | "Header" | "Footer" | "TableCell" | "Footnote" | "Endnote" | "NoteItem"

Remarks

[ API set: WordApi 1.3 ]

Method Details

clear()

Clears the contents of the body object. The user can perform the undo operation on the cleared content.

clear(): void;

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to clear the contents of the body.
    body.clear();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();

    console.log('Cleared the body contents.');
});

// The Silly stories add-in sample shows how the 
// clear method can be used to clear the contents of a document.
// https://aka.ms/sillystorywordaddin

getComments()

Gets comments associated with the body.

getComments(): Word.CommentCollection;

Returns

Remarks

[ API set: WordApiOnline 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-comments.yaml
// Get the comments in the document body.
await Word.run(async (context) => {
  const comments = context.document.body.getComments();

  // Load objects for display in Script Lab console.
  comments.load();
  await context.sync();

  console.log("All comments:");
  console.log(comments);
});

getHtml()

Gets an HTML representation of the body object. When rendered in a web page or HTML viewer, the formatting will be a close, but not exact, match for of the formatting of the document. This method does not return the exact same HTML for the same document on different platforms (Windows, Mac, Word on the web, etc.). If you need exact fidelity, or consistency across platforms, use Body.getOoxml() and convert the returned XML to HTML.

getHtml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to get the HTML contents of the body.
    const bodyHTML = body.getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log("Body HTML contents: " + bodyHTML.value);
});

getOoxml()

Gets the OOXML (Office Open XML) representation of the body object.

getOoxml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to get the OOXML contents of the body.
    const bodyOOXML = body.getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log("Body OOXML contents: " + bodyOOXML.value);
});

getRange(rangeLocation)

Gets the whole body, or the starting or ending point of the body, as a range.

getRange(rangeLocation?: Word.RangeLocation): Word.Range;

Parameters

rangeLocation
Word.RangeLocation

Optional. The range location must be 'Whole', 'Start', 'End', 'After', or 'Content'.

Returns

Remarks

[ API set: WordApi 1.3 ]

getRange(rangeLocationString)

Gets the whole body, or the starting or ending point of the body, as a range.

getRange(rangeLocationString?: "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range;

Parameters

rangeLocationString

"Whole" | "Start" | "End" | "Before" | "After" | "Content"

Optional. The range location must be 'Whole', 'Start', 'End', 'After', or 'Content'.

Returns

Remarks

[ API set: WordApi 1.3 ]

getReviewedText(changeTrackingVersion)

Gets reviewed text based on ChangeTrackingVersion selection.

getReviewedText(changeTrackingVersion?: Word.ChangeTrackingVersion): OfficeExtension.ClientResult<string>;

Parameters

changeTrackingVersion
Word.ChangeTrackingVersion

Optional. The value must be 'Original' or 'Current'. The default is 'Current'.

Returns

Remarks

[ API set: WordApiOnline 1.1 ]

getReviewedText(changeTrackingVersionString)

Gets reviewed text based on ChangeTrackingVersion selection.

getReviewedText(changeTrackingVersionString?: "Original" | "Current"): OfficeExtension.ClientResult<string>;

Parameters

changeTrackingVersionString

"Original" | "Current"

Optional. The value must be 'Original' or 'Current'. The default is 'Current'.

Returns

Remarks

[ API set: WordApiOnline 1.1 ]

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document.

insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void;

Parameters

breakType
Word.BreakType

Required. The break type to add to the body.

insertLocation
Word.InsertLocation

Required. The value must be 'Start' or 'End'.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert a page break at the start of the document body.
    body.insertBreak(Word.BreakType.page, Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Added a page break at the start of the document body.');
});

insertBreak(breakTypeString, insertLocation)

Inserts a break at the specified location in the main document.

insertBreak(breakTypeString: "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): void;

Parameters

breakTypeString

"Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Required. The break type to add to the body.

insertLocation

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Start' or 'End'.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

insertContentControl()

Wraps the body object with a Rich Text content control.

insertContentControl(): Word.ContentControl;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to wrap the body in a content control.
    body.insertContentControl();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Wrapped the body in a content control.');
});

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the body at the specified location.

insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

base64File

string

Required. The base64 encoded content of a .docx file.

insertLocation
Word.InsertLocation

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert base64 encoded .docx at the beginning of the content body.
    // You will need to implement getBase64() to pass in a string of a base64 encoded docx file.
    body.insertFileFromBase64(getBase64(), Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Added base64 encoded text to the beginning of the document body.');
});

insertFileFromBase64(base64File, insertLocationString)

Inserts a document into the body at the specified location.

insertFileFromBase64(base64File: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

base64File

string

Required. The base64 encoded content of a .docx file.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

html

string

Required. The HTML to be inserted in the document.

insertLocation
Word.InsertLocation

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert HTML in to the beginning of the body.
    body.insertHtml(
        '<strong>This is text inserted with body.insertHtml()</strong>', Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('HTML added to the beginning of the document body.');
});

insertHtml(html, insertLocationString)

Inserts HTML at the specified location.

insertHtml(html: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

html

string

Required. The HTML to be inserted in the document.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation): Word.InlinePicture;

Parameters

base64EncodedImage

string

Required. The base64 encoded image to be inserted in the body.

insertLocation
Word.InsertLocation

Required. The value must be 'Start' or 'End'.

Returns

Remarks

[ API set: WordApi 1.2 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert OOXML in to the beginning of the body.
    body.insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('OOXML added to the beginning of the document body.');
});

// Read "Create better add-ins for Word with Office Open XML" for guidance on working with OOXML.
// https://docs.microsoft.com/office/dev/add-ins/word/create-better-add-ins-for-word-with-office-open-xml

// The Word-Add-in-DocumentAssembly sample shows how you can use this API to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly

insertInlinePictureFromBase64(base64EncodedImage, insertLocationString)

Inserts a picture into the body at the specified location.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture;

Parameters

base64EncodedImage

string

Required. The base64 encoded image to be inserted in the body.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Start' or 'End'.

Returns

Remarks

[ API set: WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

ooxml

string

Required. The OOXML to be inserted.

insertLocation
Word.InsertLocation

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

insertOoxml(ooxml, insertLocationString)

Inserts OOXML at the specified location.

insertOoxml(ooxml: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

ooxml

string

Required. The OOXML to be inserted.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph;

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocation
Word.InsertLocation

Required. The value must be 'Start' or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert the paragraph at the end of the document body.
    body.insertParagraph('Content of a new paragraph', Word.InsertLocation.end);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Paragraph added at the end of the document body.');
});

// The Word-Add-in-DocumentAssembly sample shows how you can use the insertParagraph method to assemble a document.
// https://github.com/OfficeDev/Word-Add-in-DocumentAssembly

insertParagraph(paragraphText, insertLocationString)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph;

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Start' or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/insert-formatted-text.yaml
await Word.run(async (context) => {
  // Second sentence, let's insert it as a paragraph after the previously inserted one.
  const secondSentence = context.document.body.insertParagraph(
    "This is the first text with a custom style.",
    "End"
  );
  secondSentence.font.set({
    bold: false,
    italic: true,
    name: "Berlin Sans FB",
    color: "blue",
    size: 30
  });

  await context.sync();
});

insertTable(rowCount, columnCount, insertLocation, values)

Inserts a table with the specified number of rows and columns.

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table;

Parameters

rowCount

number

Required. The number of rows in the table.

columnCount

number

Required. The number of columns in the table.

insertLocation
Word.InsertLocation

Required. The value must be 'Start' or 'End'.

values

string[][]

Optional 2D array. Cells are filled if the corresponding strings are specified in the array.

Returns

Remarks

[ API set: WordApi 1.3 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/table-cell-access.yaml
await Word.run(async (context) => {
  // Use a two-dimensional array to hold the initial table values.
  const data = [
    ["Tokyo", "Beijing", "Seattle"],
    ["Apple", "Orange", "Pineapple"]
  ];
  const table = context.document.body.insertTable(2, 3, "Start", data);
  table.styleBuiltIn = Word.Style.gridTable5Dark_Accent2;
  table.styleFirstColumn = false;

  await context.sync();
});

insertTable(rowCount, columnCount, insertLocationString, values)

Inserts a table with the specified number of rows and columns.

insertTable(rowCount: number, columnCount: number, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace", values?: string[][]): Word.Table;

Parameters

rowCount

number

Required. The number of rows in the table.

columnCount

number

Required. The number of columns in the table.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Start' or 'End'.

values

string[][]

Optional 2D array. Cells are filled if the corresponding strings are specified in the array.

Returns

Remarks

[ API set: WordApi 1.3 ]

insertText(text, insertLocation)

Inserts text into the body at the specified location.

insertText(text: string, insertLocation: Word.InsertLocation): Word.Range;

Parameters

text

string

Required. Text to be inserted.

insertLocation
Word.InsertLocation

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to insert text in to the beginning of the body.
    body.insertText('This is text inserted with body.insertText()', Word.InsertLocation.start);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Text added to the beginning of the document body.');
});

insertText(text, insertLocationString)

Inserts text into the body at the specified location.

insertText(text: string, insertLocationString: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range;

Parameters

text

string

Required. Text to be inserted.

insertLocationString

"Before" | "After" | "Start" | "End" | "Replace"

Required. The value must be 'Replace', 'Start', or 'End'.

Returns

Remarks

[ API set: WordApi 1.1 ]

load(options)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(options?: Word.Interfaces.BodyLoadOptions): Word.Body;

Parameters

options
Word.Interfaces.BodyLoadOptions

Provides options for which properties of the object to load.

Returns

load(propertyNames)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNames?: string | string[]): Word.Body;

Parameters

propertyNames

string | string[]

A comma-delimited string or an array of strings that specify the properties to load.

Returns

load(propertyNamesAndPaths)

Queues up a command to load the specified properties of the object. You must call context.sync() before reading the properties.

load(propertyNamesAndPaths?: {
            select?: string;
            expand?: string;
        }): Word.Body;

Parameters

propertyNamesAndPaths

{ select?: string; expand?: string; }

propertyNamesAndPaths.select is a comma-delimited string that specifies the properties to load, and propertyNamesAndPaths.expand is a comma-delimited string that specifies the navigation properties to load.

Returns

search(searchText, searchOptions)

Performs a search with the specified SearchOptions on the scope of the body object. The search results are a collection of range objects.

search(searchText: string, searchOptions?: Word.SearchOptions | {
            ignorePunct?: boolean;
            ignoreSpace?: boolean;
            matchCase?: boolean;
            matchPrefix?: boolean;
            matchSuffix?: boolean;
            matchWholeWord?: boolean;
            matchWildcards?: boolean;
        }): Word.RangeCollection;

Parameters

searchText

string

Required. The search text. Can be a maximum of 255 characters.

searchOptions

Word.SearchOptions | { ignorePunct?: boolean; ignoreSpace?: boolean; matchCase?: boolean; matchPrefix?: boolean; matchSuffix?: boolean; matchWholeWord?: boolean; matchWildcards?: boolean; }

Optional. Options for the search.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/search.yaml
await Word.run(async (context) => {
  const results = context.document.body.search("Online");
  results.load("length");

  await context.sync();

  // Let's traverse the search results... and highlight...
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "yellow";
  }

  await context.sync();
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/search.yaml
await Word.run(async (context) => {
  // Check out how wildcard expression are built, also use the second parameter of the search method to include search modes
  // (i.e. use wildcards).
  const results = context.document.body.search("$*.[0-9][0-9]", { matchWildcards: true });
  results.load("length");

  await context.sync();

  // Let's traverse the search results... and highlight...
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "red";
    results.items[i].font.color = "white";
  }

  await context.sync();
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-word-count.yaml
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  let text = [];
  paragraphs.items.forEach((item) => {
    let paragraph = item.text.trim();
    if (paragraph) {
      paragraph.split(" ").forEach((term) => {
        let currentTerm = term.trim();
        if (currentTerm) {
          text.push(currentTerm);
        }
      });
    }
  });

  let makeTextDistinct = new Set(text);
  let distinctText = Array.from(makeTextDistinct);
  let allSearchResults = [];

  for (let i = 0; i < distinctText.length; i++) {
    let results = context.document.body.search(distinctText[i], { matchCase: true, matchWholeWord: true });
    results.load("text");

    // Map search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display counts.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

    console.log("Search term: " + result.searchTerm + " => Count: " + length);
  });
});

select(selectionMode)

Selects the body and navigates the Word UI to it.

select(selectionMode?: Word.SelectionMode): void;

Parameters

selectionMode
Word.SelectionMode

Optional. The selection mode must be 'Select', 'Start', or 'End'. 'Select' is the default.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {

    // Create a proxy object for the document body.
    const body = context.document.body;

    // Queue a command to select the document body.
    // The Word UI will move to the selected document body.
    body.select();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Selected the document body.');
});

select(selectionModeString)

Selects the body and navigates the Word UI to it.

select(selectionModeString?: "Select" | "Start" | "End"): void;

Parameters

selectionModeString

"Select" | "Start" | "End"

Optional. The selection mode must be 'Select', 'Start', or 'End'. 'Select' is the default.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

set(properties, options)

Sets multiple properties of an object at the same time. You can pass either a plain object with the appropriate properties, or another API object of the same type.

set(properties: Interfaces.BodyUpdateData, options?: OfficeExtension.UpdateOptions): void;

Parameters

properties
Word.Interfaces.BodyUpdateData

A JavaScript object with properties that are structured isomorphically to the properties of the object on which the method is called.

options
OfficeExtension.UpdateOptions

Provides an option to suppress errors if the properties object tries to set any read-only properties.

Returns

void

set(properties)

Sets multiple properties on the object at the same time, based on an existing loaded object.

set(properties: Word.Body): void;

Parameters

properties
Word.Body

Returns

void

toJSON()

Overrides the JavaScript toJSON() method in order to provide more useful output when an API object is passed to JSON.stringify(). (JSON.stringify, in turn, calls the toJSON method of the object that is passed to it.) Whereas the original Word.Body object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.BodyData) that contains shallow copies of any loaded child properties from the original object.

toJSON(): Word.Interfaces.BodyData;

Returns

track()

Track the object for automatic adjustment based on surrounding changes in the document. This call is a shorthand for context.trackedObjects.add(thisObject). If you are using this object across .sync calls and outside the sequential execution of a ".run" batch, and get an "InvalidObjectPath" error when setting a property or invoking a method on the object, you need to add the object to the tracked object collection when the object was first created. If this object is part of a collection, you should also track the parent collection.

track(): Word.Body;

Returns

untrack()

Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call context.sync() before the memory release takes effect.

untrack(): Word.Body;

Returns