Word.Range class

Represents a contiguous area in a document.

Extends

Remarks

[ API set: WordApi 1.1 ]

Properties

contentControls

Gets the collection of content control objects in the range.

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

fields

Gets the collection of field objects in the range.

font

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

footnotes

Gets the collection of footnotes in the range.

hyperlink

Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part.

inlinePictures

Gets the collection of inline picture objects in the range.

isEmpty

Checks whether the range length is zero.

lists

Gets the collection of list objects in the range.

paragraphs

Gets the collection of paragraph objects in the range.

parentBody

Gets the parent body of the range.

parentContentControl

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

parentContentControlOrNullObject

Gets the currently supported content control that contains the range. If there isn't a parent content control, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

parentTable

Gets the table that contains the range. Throws an ItemNotFound error if it isn't contained in a table.

parentTableCell

Gets the table cell that contains the range. Throws an ItemNotFound error if it isn't contained in a table cell.

parentTableCellOrNullObject

Gets the table cell that contains the range. If it isn't contained in a table cell, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

parentTableOrNullObject

Gets the table that contains the range. If it isn't contained in a table, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

style

Specifies the style name for the range. 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

Specifies the built-in style name for the range. 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 range.

text

Gets the text of the range.

Methods

clear()

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

compareLocationWith(range)

Compares this range's location with another range's location.

delete()

Deletes the range and its content from the document.

expandTo(range)

Returns a new range that extends from this range in either direction to cover another range. This range isn't changed. Throws an ItemNotFound error if the two ranges do not have a union.

expandToOrNullObject(range)

Returns a new range that extends from this range in either direction to cover another range. This range isn't changed. If the two ranges don't have a union, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getBookmarks(includeHidden, includeAdjacent)

Gets the names all bookmarks in or overlapping the range. A bookmark is hidden if its name starts with the underscore character.

getComments()

Gets comments associated with the range.

getContentControls(options)

Gets the currently supported content controls in the range.

getHtml()

Gets an HTML representation of the range 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 Range.getOoxml() and convert the returned XML to HTML.

getHyperlinkRanges()

Gets hyperlink child ranges within the range.

getNextTextRange(endingMarks, trimSpacing)

Gets the next text range by using punctuation marks and/or other ending marks. Throws an ItemNotFound error if this text range is the last one.

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

Gets the next text range by using punctuation marks and/or other ending marks. If this text range is the last one, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getOoxml()

Gets the OOXML representation of the range object.

getRange(rangeLocation)

Clones the range, or gets the starting or ending point of the range as a new range.

getReviewedText(changeTrackingVersion)

Gets reviewed text based on ChangeTrackingVersion selection.

getReviewedText(changeTrackingVersionString)

Gets reviewed text based on ChangeTrackingVersion selection.

getTextRanges(endingMarks, trimSpacing)

Gets the text child ranges in the range by using punctuation marks and/or other ending marks.

getTrackedChanges()

Gets the collection of the TrackedChange objects in the range.

highlight()

Highlights the range temporarily without changing document content. To highlight the text permanently, set the range's Font.HighlightColor.

insertBookmark(name)

Inserts a bookmark on the range. If a bookmark of the same name exists somewhere, it is deleted first.

insertBreak(breakType, insertLocation)

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

insertComment(commentText)

Insert a comment on the range.

insertContentControl(contentControlType)

Wraps the Range object with a content control.

insertEndnote(insertText)

Inserts an endnote. The endnote reference is placed after the range.

insertField(insertLocation, fieldType, text, removeFormatting)

Inserts a field at the specified location.

insertField(insertLocation, fieldTypeString, text, removeFormatting)

Inserts a field at the specified location.

insertFileFromBase64(base64File, insertLocation)

Inserts a document at the specified location.

insertFootnote(insertText)

Inserts a footnote. The footnote reference is placed after the range.

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture at the specified location.

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertTable(rowCount, columnCount, insertLocation, values)

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

insertText(text, insertLocation)

Inserts text at the specified location.

intersectWith(range)

Returns a new range as the intersection of this range with another range. This range isn't changed. Throws an ItemNotFound error if the two ranges aren't overlapped or adjacent.

intersectWithOrNullObject(range)

Returns a new range as the intersection of this range with another range. This range isn't changed. If the two ranges aren't overlapped or adjacent, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

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.

removeHighlight()

Removes the highlight added by the Highlight function if any.

search(searchText, searchOptions)

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

select(selectionMode)

Selects and navigates the Word UI to the range.

select(selectionModeString)

Selects and navigates the Word UI to the range.

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.

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

Splits the range into child ranges by using delimiters.

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.Range object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.RangeData) 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.

Events

onCommentAdded

Occurs when new comments are added.

onCommentChanged

Occurs when a comment or its reply is changed.

onCommentDeselected

Occurs when a comment is deselected.

onCommentSelected

Occurs when a comment is selected.

Property Details

contentControls

Gets the collection of content control objects in the range.

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

readonly endnotes: Word.NoteItemCollection;

Property Value

Remarks

[ API set: WordApi 1.5 ]

fields

Gets the collection of field objects in the range.

readonly fields: Word.FieldCollection;

Property Value

Remarks

[ API set: WordApi 1.4 ]

font

Gets the text format of the range. 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 ]

footnotes

Gets the collection of footnotes in the range.

readonly footnotes: Word.NoteItemCollection;

Property Value

Remarks

[ API set: WordApi 1.5 ]

Examples

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

// Gets the footnotes in the selected document range.
await Word.run(async (context) => {
  const footnotes = context.document.getSelection().footnotes;
  footnotes.load("length");
  await context.sync();

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

Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part.

hyperlink: string;

Property Value

string

Remarks

[ API set: WordApi 1.3 ]

inlinePictures

Gets the collection of inline picture objects in the range.

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

Remarks

[ API set: WordApi 1.2 ]

isEmpty

Checks whether the range length is zero.

readonly isEmpty: boolean;

Property Value

boolean

Remarks

[ API set: WordApi 1.3 ]

lists

Gets the collection of list objects in the range.

readonly lists: Word.ListCollection;

Property Value

Remarks

[ API set: WordApi 1.3 ]

paragraphs

Gets the collection of paragraph objects in the range.

readonly paragraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

Important: For requirement sets 1.1 and 1.2, paragraphs in tables wholly contained within this range aren't returned. From requirement set 1.3, paragraphs in such tables are also returned.

parentBody

Gets the parent body of the range.

readonly parentBody: Word.Body;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentContentControl

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

readonly parentContentControl: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.1 ]

parentContentControlOrNullObject

Gets the currently supported content control that contains the range. If there isn't a parent content control, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

readonly parentContentControlOrNullObject: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentTable

Gets the table that contains the range. Throws an ItemNotFound error if it isn't contained in a table.

readonly parentTable: Word.Table;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentTableCell

Gets the table cell that contains the range. Throws an ItemNotFound error if it isn't contained in a table cell.

readonly parentTableCell: Word.TableCell;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentTableCellOrNullObject

Gets the table cell that contains the range. If it isn't contained in a table cell, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

readonly parentTableCellOrNullObject: Word.TableCell;

Property Value

Remarks

[ API set: WordApi 1.3 ]

parentTableOrNullObject

Gets the table that contains the range. If it isn't contained in a table, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

readonly parentTableOrNullObject: Word.Table;

Property Value

Remarks

[ API set: WordApi 1.3 ]

style

Specifies the style name for the range. 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

Specifies the built-in style name for the range. 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.BuiltInStyleName | "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.BuiltInStyleName | "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 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/90-scenarios/doc-assembly.yaml

await Word.run(async (context) => {
    const header = context.document.body.insertText("This is a sample Heading 1 Title!!\n",
        "Start" /*this means at the beginning of the body */);
    header.styleBuiltIn = Word.BuiltInStyleName.heading1;

    await context.sync();
});

tables

Gets the collection of table objects in the range.

readonly tables: Word.TableCollection;

Property Value

Remarks

[ API set: WordApi 1.3 ]

text

Gets the text of the range.

readonly text: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Method Details

clear()

Clears the contents of the range 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) => {

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to clear the contents of the proxy range object.
    range.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 selection (range object)');
});

compareLocationWith(range)

Compares this range's location with another range's location.

compareLocationWith(range: Word.Range): OfficeExtension.ClientResult<Word.LocationRelation>;

Parameters

range
Word.Range

Required. The range to compare with this range.

Returns

Remarks

[ API set: WordApi 1.3 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml

// Compares the location of one paragraph in relation to another paragraph.
await Word.run(async (context) => {
  const paragraphs = context.document.body.paragraphs;
  paragraphs.load("items");

  await context.sync();

  const firstParagraphAsRange = paragraphs.items[0].getRange();
  const secondParagraphAsRange = paragraphs.items[1].getRange();

  const comparedLocation = firstParagraphAsRange.compareLocationWith(secondParagraphAsRange);

  await context.sync();

  console.log(`Location of the first paragraph in relation to the second paragraph: ${comparedLocation.value}`);
});

delete()

Deletes the range and its content from the document.

delete(): void;

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to delete the range object.
    range.delete();

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

expandTo(range)

Returns a new range that extends from this range in either direction to cover another range. This range isn't changed. Throws an ItemNotFound error if the two ranges do not have a union.

expandTo(range: Word.Range): Word.Range;

Parameters

range
Word.Range

Required. Another range.

Returns

Remarks

[ API set: WordApi 1.3 ]

expandToOrNullObject(range)

Returns a new range that extends from this range in either direction to cover another range. This range isn't changed. If the two ranges don't have a union, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

expandToOrNullObject(range: Word.Range): Word.Range;

Parameters

range
Word.Range

Required. Another range.

Returns

Remarks

[ API set: WordApi 1.3 ]

getBookmarks(includeHidden, includeAdjacent)

Gets the names all bookmarks in or overlapping the range. A bookmark is hidden if its name starts with the underscore character.

getBookmarks(includeHidden?: boolean, includeAdjacent?: boolean): OfficeExtension.ClientResult<string[]>;

Parameters

includeHidden

boolean

Optional. Indicates whether to include hidden bookmarks. Default is false which indicates that the hidden bookmarks are excluded.

includeAdjacent

boolean

Optional. Indicates whether to include bookmarks that are adjacent to the range. Default is false which indicates that the adjacent bookmarks are excluded.

Returns

Remarks

[ API set: WordApi 1.4 ]

getComments()

Gets comments associated with the range.

getComments(): Word.CommentCollection;

Returns

Remarks

[ API set: WordApi 1.4 ]

Examples

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

// Gets the comments in the selected content.
await Word.run(async (context) => {
  const comments = context.document.getSelection().getComments();

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

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

getContentControls(options)

Gets the currently supported content controls in the range.

getContentControls(options?: Word.ContentControlOptions): Word.ContentControlCollection;

Parameters

options
Word.ContentControlOptions

Optional. Options that define which content controls are returned.

Returns

Remarks

[ API set: WordApi 1.5 ]

Important: If specific types are provided in the options parameter, only content controls of supported types are returned. Be aware that an exception will be thrown on using methods of a generic Word.ContentControl that aren't relevant for the specific type. With time, additional types of content controls may be supported. Therefore, your add-in should request and handle specific types of content controls.

getHtml()

Gets an HTML representation of the range 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 Range.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) => {

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to get the HTML of the current selection.
    const html = range.getHtml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('The HTML read from the document was: ' + html.value);
});

getHyperlinkRanges()

Gets hyperlink child ranges within the range.

getHyperlinkRanges(): Word.RangeCollection;

Returns

Remarks

[ API set: WordApi 1.3 ]

Examples

await Word.run(async (context) => {
    // Get the entire document body.
    const bodyRange = context.document.body.getRange(Word.RangeLocation.whole);

    // Get all the ranges that only consist of hyperlinks.
    const hyperLinks = bodyRange.getHyperlinkRanges();
    hyperLinks.load("hyperlink");
    await context.sync();

    // Log each hyperlink.
    hyperLinks.items.forEach((linkRange) => {
        console.log(linkRange.hyperlink);
    });
});

getNextTextRange(endingMarks, trimSpacing)

Gets the next text range by using punctuation marks and/or other ending marks. Throws an ItemNotFound error if this text range is the last one.

getNextTextRange(endingMarks: string[], trimSpacing?: boolean): Word.Range;

Parameters

endingMarks

string[]

Required. The punctuation marks and/or other ending marks as an array of strings.

trimSpacing

boolean

Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included.

Returns

Remarks

[ API set: WordApi 1.3 ]

getNextTextRangeOrNullObject(endingMarks, trimSpacing)

Gets the next text range by using punctuation marks and/or other ending marks. If this text range is the last one, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

getNextTextRangeOrNullObject(endingMarks: string[], trimSpacing?: boolean): Word.Range;

Parameters

endingMarks

string[]

Required. The punctuation marks and/or other ending marks as an array of strings.

trimSpacing

boolean

Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included.

Returns

Remarks

[ API set: WordApi 1.3 ]

getOoxml()

Gets the OOXML representation of the range 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) => {

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to get the OOXML of the current selection.
    const ooxml = range.getOoxml();

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('The OOXML read from the document was:  ' + ooxml.value);
});

getRange(rangeLocation)

Clones the range, or gets the starting or ending point of the range as a new range.

getRange(rangeLocation?: Word.RangeLocation.whole | Word.RangeLocation.start | Word.RangeLocation.end | Word.RangeLocation.after | Word.RangeLocation.content | "Whole" | "Start" | "End" | "After" | "Content"): Word.Range;

Parameters

rangeLocation

whole | start | end | after | content | "Whole" | "Start" | "End" | "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: WordApi 1.4 ]

Examples

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

// Gets the reviewed text.
await Word.run(async (context) => {
  const range = context.document.getSelection();
  const before = range.getReviewedText(Word.ChangeTrackingVersion.original);
  const after = range.getReviewedText(Word.ChangeTrackingVersion.current);

  await context.sync();

  console.log(`Reviewed text (before):\n${before.value}`);
  console.log(`Reviewed text (after):\n${after.value}`);
});

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: WordApi 1.4 ]

getTextRanges(endingMarks, trimSpacing)

Gets the text child ranges in the range by using punctuation marks and/or other ending marks.

getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;

Parameters

endingMarks

string[]

Required. The punctuation marks and/or other ending marks as an array of strings.

trimSpacing

boolean

Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection.

Returns

Remarks

[ API set: WordApi 1.3 ]

Examples

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

await Word.run(async (context) => {
  // Get the complete sentence (as range) associated with the insertion point.
  const sentences = context.document
    .getSelection()
    .getTextRanges(["."] /* Using the "." as delimiter */, false /*means without trimming spaces*/);
  sentences.load("$none");
  await context.sync();

  // Expand the range to the end of the paragraph to get all the complete sentences.
  const sentencesToTheEndOfParagraph = sentences.items[0]
    .getRange()
    .expandTo(
      context.document
        .getSelection()
        .paragraphs.getFirst()
        .getRange(Word.RangeLocation.end)
    )
    .getTextRanges(["."], false /* Don't trim spaces*/);
  sentencesToTheEndOfParagraph.load("text");
  await context.sync();

  for (let i = 0; i < sentencesToTheEndOfParagraph.items.length; i++) {
    console.log(sentencesToTheEndOfParagraph.items[i].text);
  }
});

getTrackedChanges()

Gets the collection of the TrackedChange objects in the range.

getTrackedChanges(): Word.TrackedChangeCollection;

Returns

Remarks

[ API set: WordApi 1.6 ]

highlight()

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.

Highlights the range temporarily without changing document content. To highlight the text permanently, set the range's Font.HighlightColor.

highlight(): void;

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

insertBookmark(name)

Inserts a bookmark on the range. If a bookmark of the same name exists somewhere, it is deleted first.

insertBookmark(name: string): void;

Parameters

name

string

Required. The case-insensitive bookmark name. Only alphanumeric and underscore characters are supported. It must begin with a letter but if you want to tag the bookmark as hidden, then start the name with an underscore character. Names can't be longer than 40 characters.

Returns

void

Remarks

[ API set: WordApi 1.4 ]

Note: The conditions of inserting a bookmark are similar to doing so in the Word UI. To learn more about managing bookmarks in the Word UI, see Add or delete bookmarks in a Word document or Outlook message.

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.before | Word.InsertLocation.after | "Before" | "After"): void;

Parameters

breakType

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

Required. The break type to add.

insertLocation

before | after | "Before" | "After"

Required. The value must be 'Before' or 'After'.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert a page break after the selected text.
    range.insertBreak(Word.BreakType.page, Word.InsertLocation.after);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    console.log('Inserted a page break after the selected text.');
});

insertComment(commentText)

Insert a comment on the range.

insertComment(commentText: string): Word.Comment;

Parameters

commentText

string

Required. The comment text to be inserted.

Returns

comment object

Remarks

[ API set: WordApi 1.4 ]

Examples

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

// Sets a comment on the selected content.
await Word.run(async (context) => {
  const text = $("#comment-text")
    .val()
    .toString();
  const comment = context.document.getSelection().insertComment(text);

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

  console.log("Comment inserted:");
  console.log(comment);
});

insertContentControl(contentControlType)

Wraps the Range 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/90-scenarios/doc-assembly.yaml

// Simulates creation of a template. First searches the document for instances of the string "Contractor",
// then changes the format  of each search result,
// then wraps each search result within a content control,
// finally sets a tag and title property on each content control.
await Word.run(async (context) => {
    const results = context.document.body.search("Contractor");
    results.load("font/bold");

    // Check to make sure these content controls haven't been added yet.
    const customerContentControls = context.document.contentControls.getByTag("customer");
    customerContentControls.load("text");
    await context.sync();

  if (customerContentControls.items.length === 0) {
    for (let i = 0; i < results.items.length; i++) { 
        results.items[i].font.bold = true;
        let cc = results.items[i].insertContentControl();
        cc.tag = "customer";  // This value is used in the next step of this sample.
        cc.title = "Customer Name " + i;
    }
  }
    await context.sync();
});

insertEndnote(insertText)

Inserts an endnote. The endnote reference is placed after the range.

insertEndnote(insertText?: string): Word.NoteItem;

Parameters

insertText

string

Optional. Text to be inserted into the endnote body. The default is "".

Returns

Remarks

[ API set: WordApi 1.5 ]

insertField(insertLocation, fieldType, text, removeFormatting)

Inserts a field at the specified location.

insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: Word.FieldType, text?: string, removeFormatting?: boolean): Word.Field;

Parameters

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

Required. The location relative to the range where the field will be inserted. The value must be 'Replace', 'Start', 'End', 'Before', or 'After'.

fieldType
Word.FieldType

Optional. Can be any FieldType constant. The default value is Empty.

text

string

Optional. Additional properties or options if needed for specified field type.

removeFormatting

boolean

Optional. true to remove the formatting that's applied to the field during updates, false otherwise. The default value is false.

Returns

Remarks

[ API set: WordApi 1.5 ]

Important:

In Word on Windows and on Mac, the API supports inserting and managing all types listed in Word.FieldType except Word.FieldType.others.

In Word on the web, the API supports inserting and managing the following field types.

  • Word.FieldType.addin

  • Word.FieldType.date

  • Word.FieldType.hyperlink

  • Word.FieldType.toc

Examples

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

// Inserts a Date field before selection.
await Word.run(async (context) => {
  var range = context.document.getSelection().getRange();

  const field = range.insertField(Word.InsertLocation.before, Word.FieldType.date, '\\@ "M/d/yyyy h:mm am/pm"', true);

  field.load("result,code");
  await context.sync();

  if (field.isNullObject) {
    console.log("There are no fields in this document.");
  } else {
    console.log("Code of the field: " + field.code);
    console.log("Result of the field: " + JSON.stringify(field.result));
  }
});

insertField(insertLocation, fieldTypeString, text, removeFormatting)

Inserts a field at the specified location.

insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldTypeString?: "Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined", text?: string, removeFormatting?: boolean): Word.Field;

Parameters

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

Required. The location relative to the range where the field will be inserted. The value must be 'Replace', 'Start', 'End', 'Before', or 'After'.

fieldTypeString

"Addin" | "AddressBlock" | "Advance" | "Ask" | "Author" | "AutoText" | "AutoTextList" | "BarCode" | "Bibliography" | "BidiOutline" | "Citation" | "Comments" | "Compare" | "CreateDate" | "Data" | "Database" | "Date" | "DisplayBarcode" | "DocProperty" | "DocVariable" | "EditTime" | "Embedded" | "EQ" | "Expression" | "FileName" | "FileSize" | "FillIn" | "FormCheckbox" | "FormDropdown" | "FormText" | "GotoButton" | "GreetingLine" | "Hyperlink" | "If" | "Import" | "Include" | "IncludePicture" | "IncludeText" | "Index" | "Info" | "Keywords" | "LastSavedBy" | "Link" | "ListNum" | "MacroButton" | "MergeBarcode" | "MergeField" | "MergeRec" | "MergeSeq" | "Next" | "NextIf" | "NoteRef" | "NumChars" | "NumPages" | "NumWords" | "OCX" | "Page" | "PageRef" | "Print" | "PrintDate" | "Private" | "Quote" | "RD" | "Ref" | "RevNum" | "SaveDate" | "Section" | "SectionPages" | "Seq" | "Set" | "Shape" | "SkipIf" | "StyleRef" | "Subject" | "Subscriber" | "Symbol" | "TA" | "TC" | "Template" | "Time" | "Title" | "TOA" | "TOC" | "UserAddress" | "UserInitials" | "UserName" | "XE" | "Empty" | "Others" | "Undefined"

Optional. Can be any FieldType constant. The default value is Empty.

text

string

Optional. Additional properties or options if needed for specified field type.

removeFormatting

boolean

Optional. true to remove the formatting that's applied to the field during updates, false otherwise. The default value is false.

Returns

Remarks

[ API set: WordApi 1.5 ]

Important:

In Word on Windows and on Mac, the API supports inserting and managing all types listed in Word.FieldType except Word.FieldType.others.

In Word on the web, the API supports inserting and managing the following field types.

  • Word.FieldType.addin

  • Word.FieldType.date

  • Word.FieldType.hyperlink

  • Word.FieldType.toc

insertFileFromBase64(base64File, insertLocation)

Inserts a document at the specified location.

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

Parameters

base64File

string

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

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

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

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert base64 encoded .docx at the beginning of the range.
    // You'll need to implement getBase64() to make this work.
    range.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 range.');
});

insertFootnote(insertText)

Inserts a footnote. The footnote reference is placed after the range.

insertFootnote(insertText?: string): Word.NoteItem;

Parameters

insertText

string

Optional. Text to be inserted into the footnote body. The default is "".

Returns

Remarks

[ API set: WordApi 1.5 ]

Examples

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

// Sets a footnote on the selected content.
await Word.run(async (context) => {
  const text = $("#input-footnote")
    .val()
    .toString();
  const footnote = context.document.getSelection().insertFootnote(text);
  await context.sync();

  console.log("Inserted footnote.");
});

insertHtml(html, insertLocation)

Inserts HTML at the specified location.

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

Parameters

html

string

Required. The HTML to be inserted.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert HTML in to the beginning of the range.
    range.insertHtml('<strong>This is text inserted with range.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 range.');
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts a picture at the specified location.

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

Parameters

base64EncodedImage

string

Required. The Base64-encoded image to be inserted.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

Returns

Remarks

[ API set: WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

Inserts OOXML at the specified location.

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

Parameters

ooxml

string

Required. The OOXML to be inserted.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert OOXML in to the beginning of the range.
    range.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 range.');
});

// Read "Create better add-ins for Word with Office Open XML" 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

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After"): Word.Paragraph;

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocation

before | after | "Before" | "After"

Required. The value must be 'Before' or 'After'.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert the paragraph after the range.
    range.insertParagraph('Content of a new paragraph', Word.InsertLocation.after);

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

insertTable(rowCount, columnCount, insertLocation, values)

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

insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation.before | Word.InsertLocation.after | "Before" | "After", 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

before | after | "Before" | "After"

Required. The value must be 'Before' or 'After'.

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 at the specified location.

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

Parameters

text

string

Required. Text to be inserted.

insertLocation

Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"

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

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

    // Queue a command to insert the paragraph at the end of the range.
    range.insertText('New text inserted into the range.', 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('Text added to the end of the range.');
});

intersectWith(range)

Returns a new range as the intersection of this range with another range. This range isn't changed. Throws an ItemNotFound error if the two ranges aren't overlapped or adjacent.

intersectWith(range: Word.Range): Word.Range;

Parameters

range
Word.Range

Required. Another range.

Returns

Remarks

[ API set: WordApi 1.3 ]

intersectWithOrNullObject(range)

Returns a new range as the intersection of this range with another range. This range isn't changed. If the two ranges aren't overlapped or adjacent, then this method will return an object with its isNullObject property set to true. For further information, see *OrNullObject methods and properties.

intersectWithOrNullObject(range: Word.Range): Word.Range;

Parameters

range
Word.Range

Required. Another range.

Returns

Remarks

[ API set: WordApi 1.3 ]

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.RangeLoadOptions): Word.Range;

Parameters

options
Word.Interfaces.RangeLoadOptions

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.Range;

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.Range;

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

removeHighlight()

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.

Removes the highlight added by the Highlight function if any.

removeHighlight(): void;

Returns

void

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

search(searchText, searchOptions)

Performs a search with the specified SearchOptions on the scope of the range 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.

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 ]

select(selectionMode)

Selects and navigates the Word UI to the range.

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) => {

    // Queue a command to get the current selection and then
    // create a proxy range object with the results.
    const range = context.document.getSelection();

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

    // Queue a command to select the HTML that was inserted.
    range.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 range.');
});

select(selectionModeString)

Selects and navigates the Word UI to the range.

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.RangeUpdateData, options?: OfficeExtension.UpdateOptions): void;

Parameters

properties
Word.Interfaces.RangeUpdateData

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.Range): void;

Parameters

properties
Word.Range

Returns

void

split(delimiters, multiParagraphs, trimDelimiters, trimSpacing)

Splits the range into child ranges by using delimiters.

split(delimiters: string[], multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection;

Parameters

delimiters

string[]

Required. The delimiters as an array of strings.

multiParagraphs

boolean

Optional. Indicates whether a returned child range can cover multiple paragraphs. Default is false which indicates that the paragraph boundaries are also used as delimiters.

trimDelimiters

boolean

Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection.

trimSpacing

boolean

Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks, and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection.

Returns

Remarks

[ API set: WordApi 1.3 ]

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.Range object is an API object, the toJSON method returns a plain JavaScript object (typed as Word.Interfaces.RangeData) that contains shallow copies of any loaded child properties from the original object.

toJSON(): Word.Interfaces.RangeData;

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.Range;

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.Range;

Returns

Event Details

onCommentAdded

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.

Occurs when new comments are added.

readonly onCommentAdded: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Event Type

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

onCommentChanged

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.

Occurs when a comment or its reply is changed.

readonly onCommentChanged: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Event Type

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

onCommentDeselected

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.

Occurs when a comment is deselected.

readonly onCommentDeselected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Event Type

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]

onCommentSelected

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.

Occurs when a comment is selected.

readonly onCommentSelected: OfficeExtension.EventHandlers<Word.CommentEventArgs>;

Event Type

Remarks

[ API set: WordApi BETA (PREVIEW ONLY) ]