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.

font

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

paragraphs

Gets the collection of paragraph objects in 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.

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.

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.

delete()

Deletes the range and its content from the document.

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.

getOoxml()

Gets the OOXML representation of the range object.

insertBreak(breakType, insertLocation)

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

insertContentControl(contentControlType)

Wraps the Range object with a content control.

insertFileFromBase64(base64File, insertLocation)

Inserts a document at the specified location.

insertHtml(html, insertLocation)

Inserts HTML 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 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 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.

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.

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

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 ]

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.

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 ]

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 ]

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

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

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

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

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.');
});

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

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.');
});

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.');
});

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.');
});

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.');
});

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

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

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