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.

context

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

font

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

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection doesn't include floating images.

paragraphs

Gets the collection of paragraph objects in the body.

parentContentControl

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

style

Specifies 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.

text

Gets the text of the body. Use the insertText method to insert text.

Methods

clear()

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

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 doesn't 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.

insertBreak(breakType, insertLocation)

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

insertContentControl(contentControlType)

Wraps the Body object with a content control.

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the body at the specified location.

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertText(text, insertLocation)

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're 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'll 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.

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

font

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

readonly font: Word.Font;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Gets 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 font-related 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);
});

inlinePictures

Gets the collection of InlinePicture objects in the body. The collection doesn't include floating images.

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-get-pictures.yaml

// Gets the first image in the document.
await Word.run(async (context) => {
  const firstPicture = context.document.body.inlinePictures.getFirst();
  firstPicture.load("width, height");

  await context.sync();
  console.log(`Image dimensions: ${firstPicture.width} x ${firstPicture.height}`);
  // Get the image encoded as Base64.
  const base64 = firstPicture.getBase64ImageSrc();

  await context.sync();
  console.log(base64.value);
});

paragraphs

Gets the collection of paragraph objects in the body.

readonly paragraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Important: Paragraphs in tables aren't returned for requirement sets 1.1 and 1.2. From requirement set 1.3, paragraphs in tables are also returned.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-word-count.yaml

// Counts how many times each term appears in the document.
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("text");
  await context.sync();

  // Split up the document text using existing spaces as the delimiter.
  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);
        }
      });
    }
  });

  // Determine the list of unique terms.
  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 each search term with its results.
    let correlatedResults = {
      searchTerm: distinctText[i],
      hits: results
    };

    allSearchResults.push(correlatedResults);
  }

  await context.sync();

  // Display the count for each search term.
  allSearchResults.forEach((result) => {
    let length = result.hits.items.length;

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

parentContentControl

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

readonly parentContentControl: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.1 ]

style

Specifies 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 ]

text

Gets the text of the body. Use the insertText method to insert text.

readonly text: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Gets the text content of the body.
// 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 (text): " + body.text);
});

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

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Clears out the content from the document body.
// 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();

  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

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 doesn't 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

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Gets the HTML that represents the content of the body.
// 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 contents (HTML): " + 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

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Gets the OOXML that represents the content of the body.
// 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 contents (OOXML): " + bodyOOXML.value);
});

insertBreak(breakType, insertLocation)

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

insertBreak(breakType: Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line", insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): void;

Parameters

breakType

Word.BreakType | "Page" | "Next" | "SectionNext" | "SectionContinuous" | "SectionEven" | "SectionOdd" | "Line"

Required. The break type to add to the body.

insertLocation

start | end | "Start" | "End"

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

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Inserts a page break at the beginning of the document.
// 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.");
});

insertContentControl(contentControlType)

Wraps the Body object with a content control.

insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | "RichText" | "PlainText" | "CheckBox"): Word.ContentControl;

Parameters

contentControlType

richText | plainText | checkBox | "RichText" | "PlainText" | "CheckBox"

Optional. Content control type to insert. Must be 'RichText', 'PlainText', or 'CheckBox'. The default is 'RichText'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Note: The contentControlType parameter was introduced in WordApi 1.5. PlainText support was added in WordApi 1.5. CheckBox support was added in WordApi 1.7.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Creates a content control using the document body.
// 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.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

base64File

string

Required. The Base64-encoded content of a .docx file.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Note: Insertion isn't supported if the document being inserted contains an ActiveX control (likely in a form field). Consider replacing such a form field with a content control or other option appropriate for your scenario.

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Inserts the body from the external document at the beginning of this document.
// 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 Base64-encoded string representation of the body of the selected .docx file at the beginning of the current document.
  body.insertFileFromBase64(externalDocument, 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.");
});

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

insertHtml(html: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

html

string

Required. The HTML to be inserted in the document.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Required. The value must be 'Replace', '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/50-document/manage-body.yaml

// Inserts the HTML at the beginning of this document.
// 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 at the beginning of the document.
  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.");
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture into the body at the specified location.

insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.InlinePicture;

Parameters

base64EncodedImage

string

Required. The Base64-encoded image to be inserted in the body.

insertLocation

start | end | "Start" | "End"

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

Returns

Remarks

[ API set: WordApi 1.2 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Inserts an image inline at the beginning of this document.
// 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;

  // Base64-encoded image to insert inline.
  const base64EncodedImg =
    "iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC";

  // Queue a command to insert a Base64-encoded image at the beginning of the current document.
  body.insertInlinePictureFromBase64(base64EncodedImg, 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 Base64-encoded image to the beginning of the document body.");
});

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

insertOoxml(ooxml: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

ooxml

string

Required. The OOXML to be inserted.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Required. The value must be 'Replace', '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/50-document/manage-body.yaml

// Inserts OOXML at the beginning of this document.
// 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 at 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("Added OOXML to the beginning of the document body.");
});

// Read "Understand when and how to use Office Open XML in your Word add-in" for guidance on working with OOXML.
// https://learn.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

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.start | Word.InsertLocation.end | "Start" | "End"): Word.Paragraph;

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocation

start | end | "Start" | "End"

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

insertText(text, insertLocation)

Inserts text into the body at the specified location.

insertText(text: string, insertLocation: Word.InsertLocation.replace | Word.InsertLocation.start | Word.InsertLocation.end | "Replace" | "Start" | "End"): Word.Range;

Parameters

text

string

Required. Text to be inserted.

insertLocation

replace | start | end | "Replace" | "Start" | "End"

Required. The value must be 'Replace', '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/50-document/manage-body.yaml

// Inserts text at the beginning of this document.
// 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 at the beginning of the current document.
  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.');
});

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

// Does a basic text search and highlights matches in the document.
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 matches.
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "yellow";
  }

  await context.sync();
});

...

// Does a wildcard search and highlights matches in the document.
await Word.run(async (context) => {
  // Construct a wildcard expression and set matchWildcards to true in order to 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 matches.
  for (let i = 0; i < results.items.length; i++) {
    results.items[i].font.highlightColor = "red";
    results.items[i].font.color = "white";
  }

  await context.sync();
});

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

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-body.yaml

// Selects the entire body.
// 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();

  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're 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'll need to call context.sync() before the memory release takes effect.

untrack(): Word.Body;

Returns