Word.Range class
Represents a contiguous area in a document.
- Extends
Remarks
Used by
- Word.Body: getRange, insertFileFromBase64, insertHtml, insertOoxml, insertText
- Word.Bookmark: range
- Word.BookmarkCollection: add
- Word.Break: range
- Word.BuildingBlock: insert
- Word.BuildingBlockCollection: add
- Word.BuildingBlockEntryCollection: add
- Word.BuildingBlockGalleryContentControl: range
- Word.CoauthoringLock: range
- Word.CoauthoringLockAddOptions: range
- Word.CoauthoringUpdate: range
- Word.Comment: getRange
- Word.Conflict: range
- Word.ContentControl: getRange, insertFileFromBase64, insertHtml, insertOoxml, insertText
- Word.ContentControlPlaceholderOptions: range
- Word.CritiqueAnnotation: range
- Word.DatePickerContentControl: range
- Word.Document: content, getBookmarkRange, getBookmarkRangeOrNullObject, getRange, getSelection, goTo
- Word.DocumentCreated: getBookmarkRange, getBookmarkRangeOrNullObject
- Word.Editor: nextRange, range
- Word.Field: result
- Word.Frame: range
- Word.FrameCollection: add
- Word.GroupContentControl: range
- Word.HtmlDivision: range
- Word.Hyperlink: range
- Word.HyperlinkCollection: add
- Word.Index: range
- Word.IndexCollection: add, markAllEntries
- Word.InlinePicture: getRange, insertFileFromBase64, insertHtml, insertOoxml, insertText
- Word.NoteItem: reference
- Word.Page: getRange
- Word.Paragraph: getRange, insertFileFromBase64, insertHtml, insertOoxml, insertText
- Word.ParagraphCollection: add
- Word.PictureContentControl: range
- Word.RangeCollection: getFirst, getFirstOrNullObject, items
- Word.RangeScopedCollection: getItem, items
- Word.RepeatingSectionContentControl: range
- Word.RepeatingSectionItem: range
- Word.Revision: movedRange, range
- Word.Selection: formattedText, getNextRange, getPreviousRange, goTo, goToNext, goToPrevious, isEqual, isInRange, isInStory, range
- Word.Table: convertToText, getRange
- Word.TableOfAuthorities: range
- Word.TableOfAuthoritiesCollection: add, markCitation
- Word.TableOfContents: range
- Word.TableOfContentsCollection: add, markTocEntry
- Word.TableOfFigures: range
- Word.TableOfFiguresCollection: add, markTocEntry
- Word.TableRow: convertToText, range
- Word.TableRowCollection: convertToText
- Word.TrackedChange: getRange
- Word.View: collapseOutline, expandOutline
- Word.XmlNode: range
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Reads the text and checks whether the first paragraph range is empty.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
paragraphRange.load("text,isEmpty,style");
await context.sync();
console.log("First paragraph's properties:", { text: paragraphRange.text, isEmpty: paragraphRange.isEmpty, style: paragraphRange.style });
});
Properties
| bold | Specifies whether the range is formatted as bold. |
| bold |
Specifies whether the range is formatted as bold in a right-to-left language document. |
| bookmarks | Returns a |
| borders | Returns a |
| case | Specifies a |
| character |
Specifies the character width of the range. |
| combine |
Specifies if the range contains combined characters. |
| conflicts | Returns a |
| content |
Gets the collection of |
| context | The request context associated with the object. This connects the add-in's process to the Office host application's process. |
| disable |
Specifies if Microsoft Word ignores the number of characters per line for the corresponding |
| editors | Returns an |
| emphasis |
Specifies the emphasis mark for a character or designated character string. |
| end | Specifies the ending character position of the range. |
| endnotes | Gets the collection of endnotes in the range. |
| fields | Gets the collection of |
| fit |
Specifies the width (in the current measurement units) in which Microsoft Word fits the text in the current selection or 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. |
| frames | Gets a |
| grammar |
Specifies if a grammar check has been run on the range or document. |
| has |
Specifies the proofing status (spelling and grammar checking) of the range. |
| highlight |
Specifies the highlight color for the range. |
| horizontal |
Specifies the formatting for horizontal text set within vertical text. |
| 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. |
| hyperlinks | Returns a |
| id | Specifies the ID for the range. |
| inline |
Gets the collection of |
| is |
Checks whether the range length is zero. |
| is |
Gets if the range is collapsed and is located at the end-of-row mark in a table. |
| is |
Gets whether the text in the range is visible on the screen. |
| italic | Specifies if the font or range is formatted as italic. |
| italic |
Specifies if the font or range is formatted as italic (right-to-left languages). |
| kana | Specifies whether the range of Japanese language text is hiragana or katakana. |
| language |
Specifies whether Microsoft Word has detected the language of the text in the range. |
| language |
Specifies a |
| language |
Specifies an East Asian language for the range. |
| language |
Specifies a language for the range that isn't classified as an East Asian language. |
| list |
Returns a |
| lists | Gets the collection of |
| pages | Gets the collection of pages in the range. |
| paragraphs | Gets the collection of |
| parent |
Gets the parent body of the range. |
| parent |
Gets the currently supported content control that contains the range. Throws an |
| parent |
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 |
| parent |
Gets the table that contains the range. Throws an |
| parent |
Gets the table cell that contains the range. Throws an |
| parent |
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 |
| parent |
Gets the table that contains the range. If it isn't contained in a table, then this method will return an object with its |
| revisions | Gets the collection of revisions that represents the tracked changes in the range. |
| sections | Gets the collection of sections in the range. |
| shading | Returns a |
| shapes | Gets the collection of |
| show |
Specifies if all nonprinting characters (such as hidden text, tab marks, space marks, and paragraph marks) are displayed. |
| spelling |
Specifies if spelling has been checked throughout the range or document. |
| start | Specifies the starting character position of the range. |
| story |
Gets the number of characters in the story that contains the range. |
| story |
Gets the story type for the range. |
| 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 |
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. |
| table |
Gets a |
| tables | Gets the collection of |
| text | Gets the text of the range. |
| two |
Specifies whether Microsoft Word sets two lines of text in one and specifies the characters that enclose the text, if any. |
| underline | Specifies the type of underline applied to the range. |
Methods
| clear() | Clears the contents of the |
| compare |
Compares this range's location with another range's location. |
| delete() | Deletes the range and its content from the document. |
| detect |
Analyzes the range text to determine the language that it's written in. |
| expand |
Returns a new range that extends from this range in either direction to cover another range. This range isn't changed. Throws an |
| expand |
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 |
| get |
Gets the names all bookmarks in or overlapping the range. A bookmark is hidden if its name starts with the underscore character. |
| get |
Gets comments associated with the range. |
| get |
Gets the currently supported content controls in the range. |
| get |
Gets an HTML representation of the |
| get |
Gets hyperlink child ranges within the range. |
| get |
Gets the next text range by using punctuation marks and other ending marks. Throws an |
| get |
Gets the next text range by using punctuation marks and other ending marks. If this text range is the last one, then this method will return an object with its |
| get |
Gets the OOXML representation of the |
| get |
Clones the |
| get |
Gets reviewed text based on ChangeTrackingVersion selection. |
| get |
Gets reviewed text based on ChangeTrackingVersion selection. |
| get |
Gets the text child ranges in the range by using punctuation marks and other ending marks. |
| get |
Gets the collection of the |
| highlight() | Highlights the range temporarily without changing document content. To highlight the text permanently, set the range's |
| insert |
Inserts a bookmark on the range. If a bookmark of the same name exists somewhere, it is deleted first. |
| insert |
Inserts a break at the specified location in the main document. |
| insert |
Inserts a floating canvas in front of text with its anchor at the beginning of the range. |
| insert |
Insert a comment on the range. |
| insert |
Wraps the |
| insert |
Inserts an endnote. The endnote reference is placed after the range. |
| insert |
Inserts a field at the specified location. |
| insert |
Inserts a field at the specified location. |
| insert |
Inserts a document at the specified location. The maximum size of the document being inserted is 4 MB. |
| insert |
Inserts a footnote. The footnote reference is placed after the range. |
| insert |
Inserts a geometric shape in front of text with its anchor at the beginning of the range. |
| insert |
Inserts a geometric shape in front of text with its anchor at the beginning of the range. |
| insert |
Inserts HTML at the specified location. |
| insert |
Inserts a picture at the specified location. |
| insert |
Inserts OOXML at the specified location. |
| insert |
Inserts a paragraph at the specified location. |
| insert |
Inserts a floating picture in front of text with its anchor at the beginning of the range. |
| insert |
Inserts a table with the specified number of rows and columns. |
| insert |
Inserts text at the specified location. |
| insert |
Inserts a floating text box in front of text with its anchor at the beginning of the range. |
| intersect |
Returns a new range as the intersection of this range with another range. This range isn't changed. Throws an |
| intersect |
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 |
| load(options) | Queues up a command to load the specified properties of the object. You must call |
| load(property |
Queues up a command to load the specified properties of the object. You must call |
| load(property |
Queues up a command to load the specified properties of the object. You must call |
| remove |
Removes the highlight added by the |
| search(search |
Performs a search with the specified search options on the scope of the |
| select(selection |
Selects and navigates the Word UI to the range. |
| select(selection |
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, multi |
Splits the range into child ranges by using delimiters. |
| toJSON() | Overrides the JavaScript |
| 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 |
| 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 |
Events
| on |
Occurs when new comments are added. |
| on |
Occurs when a comment or its reply is changed. |
| on |
Occurs when a comment is deselected. |
| on |
Occurs when a comment is selected. |
Property Details
bold
Specifies whether the range is formatted as bold.
readonly bold: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml
// Reads character formatting on the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.load("text,bold,italic,boldBidirectional,italicBidirectional,case,highlightColorIndex");
await context.sync();
console.log("First paragraph's formatting:", {
text: paragraphRange.text,
bold: paragraphRange.bold,
italic: paragraphRange.italic,
boldBidirectional: paragraphRange.boldBidirectional,
italicBidirectional: paragraphRange.italicBidirectional,
case: paragraphRange.case,
highlightColorIndex: paragraphRange.highlightColorIndex
});
});
boldBidirectional
Specifies whether the range is formatted as bold in a right-to-left language document.
readonly boldBidirectional: boolean;
Property Value
boolean
Remarks
bookmarks
Returns a BookmarkCollection object that represents all the bookmarks in the range.
readonly bookmarks: Word.BookmarkCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml
// Read bookmark properties and the text enclosed by each bookmark.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const bookmarks: Word.BookmarkCollection = paragraphRange.bookmarks;
bookmarks.load("items/name,items/start,items/end,items/isEmpty,items/isColumn,items/storyType,items/range/text");
await context.sync();
console.log(`Bookmarks found: ${bookmarks.items.length}`);
bookmarks.items.forEach((bookmark: Word.Bookmark) => {
console.log("Bookmark details:", {
name: bookmark.name,
start: bookmark.start,
end: bookmark.end,
isEmpty: bookmark.isEmpty,
isColumn: bookmark.isColumn,
storyType: bookmark.storyType,
text: bookmark.range.text
});
});
});
borders
Returns a BorderUniversalCollection object that represents all the borders for the range.
readonly borders: Word.BorderUniversalCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/range-borders-and-shading-desktop.yaml
// Reads the border formatting of the first paragraph's text.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const borders: Word.BorderUniversalCollection = paragraphRange.borders;
borders.load("items/color,items/lineStyle,items/lineWidth,items/isVisible");
await context.sync();
console.log("First paragraph's border formatting:");
borders.items.forEach((border: Word.BorderUniversal) => {
console.log("Border:", {
color: border.color,
lineStyle: border.lineStyle,
lineWidth: border.lineWidth,
isVisible: border.isVisible
});
});
});
case
Specifies a CharacterCase value that represents the case of the text in the range.
case: Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana";
Property Value
Word.CharacterCase | "Next" | "Lower" | "Upper" | "TitleWord" | "TitleSentence" | "Toggle" | "HalfWidth" | "FullWidth" | "Katakana" | "Hiragana"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/character-formatting-and-case-desktop.yaml
// Converts the first paragraph's text to uppercase.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const characterCase: Word.CharacterCase = Word.CharacterCase.upper;
paragraphRange.case = characterCase;
await context.sync();
console.log("Converted the first paragraph's text to uppercase.");
});
characterWidth
Specifies the character width of the range.
characterWidth: Word.CharacterWidth | "Half" | "Full";
Property Value
Word.CharacterWidth | "Half" | "Full"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml
// Converts the first paragraph's Latin characters and digits to full width.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const characterWidth: Word.CharacterWidth = Word.CharacterWidth.full;
paragraphRange.characterWidth = characterWidth;
await context.sync();
console.log("Converted the first paragraph's Latin characters and digits to full width.");
});
combineCharacters
Specifies if the range contains combined characters.
combineCharacters: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml
// Combines the first paragraph's short group of characters.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.combineCharacters = true;
await context.sync();
console.log("Enabled combined characters on the first paragraph. Get layout settings to inspect the flag.");
});
conflicts
Returns a ConflictCollection object that contains all the Word.Conflict objects in the range.
readonly conflicts: Word.ConflictCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/manage-coauthoring-conflicts.yaml
// Gets coauthoring conflicts associated with the selected range.
await Word.run(async (context) => {
const selectedRange: Word.Range = context.document.getSelection();
const conflicts: Word.ConflictCollection = selectedRange.conflicts;
conflicts.load("items/type");
await context.sync();
console.log(`Conflicts in the selection: ${conflicts.items.length}`);
conflicts.items.forEach((conflict: Word.Conflict) => console.log(`Conflict type: ${conflict.type}`));
});
contentControls
Gets the collection of ContentControl objects in the range.
readonly contentControls: Word.ContentControlCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Gets the content controls contained in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const contentControls: Word.ContentControlCollection = bodyRange.contentControls;
contentControls.load("items/tag,items/title,items/text");
await context.sync();
console.log(`Content controls found: ${contentControls.items.length}`);
contentControls.items.forEach((control: Word.ContentControl) => {
console.log({ tag: control.tag, title: control.title, text: control.text });
});
});
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
disableCharacterSpaceGrid
Specifies if Microsoft Word ignores the number of characters per line for the corresponding Range object.
readonly disableCharacterSpaceGrid: boolean;
Property Value
boolean
Remarks
editors
Returns an EditorCollection object that represents all the users authorized to modify the range when the document is in protected (read-only) mode.
readonly editors: Word.EditorCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-editing-permissions-desktop.yaml
// Reads editing-permission entries for the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const editors: Word.EditorCollection = paragraphRange.editors;
const editorCount: OfficeExtension.ClientResult<number> = editors.getCount();
await context.sync();
const editorEntries: Word.Editor[] = [];
for (let index = 0; index < editorCount.value; index++) {
const editor: Word.Editor = editors.getItemAt(index);
editor.load("name,id");
editorEntries.push(editor);
}
await context.sync();
console.log(`Editing-permission entries: ${editorCount.value}`);
editorEntries.forEach((editor: Word.Editor) => console.log({ name: editor.name, id: editor.id }));
});
emphasisMark
Specifies the emphasis mark for a character or designated character string.
readonly emphasisMark: Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle";
Property Value
Word.EmphasisMark | "None" | "OverSolidCircle" | "OverComma" | "OverWhiteCircle" | "UnderSolidCircle"
Remarks
end
Specifies the ending character position of the range.
end: number;
Property Value
number
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml
// Selects the first paragraph's text except its last character.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.load("start,end");
await context.sync();
if (paragraphRange.start === paragraphRange.end) {
console.warn("The paragraph is empty. Run Set up again.");
return;
}
paragraphRange.end = paragraphRange.end - 1;
paragraphRange.select();
await context.sync();
console.log("Selected the range with its ending position reduced by one character.");
});
endnotes
Gets the collection of endnotes in the range.
readonly endnotes: Word.NoteItemCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Gets the text of every endnote in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const endnotes: Word.NoteItemCollection = bodyRange.endnotes;
endnotes.load("items/body/text");
await context.sync();
console.log(`Endnotes found: ${endnotes.items.length}`);
endnotes.items.forEach((endnote: Word.NoteItem) => console.log(endnote.body.text));
});
fields
Gets the collection of Field objects in the range.
readonly fields: Word.FieldCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Gets field codes and displayed results in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const fields: Word.FieldCollection = bodyRange.fields;
fields.load("items/code,items/result/text");
await context.sync();
console.log(`Fields found: ${fields.items.length}`);
fields.items.forEach((field: Word.Field) => console.log({ code: field.code, text: field.result.text }));
});
fitTextWidth
Specifies the width (in the current measurement units) in which Microsoft Word fits the text in the current selection or range.
fitTextWidth: number;
Property Value
number
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml
// Fits the first paragraph's text into a specified width.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.fitTextWidth = 100;
await context.sync();
console.log("Fitted the first paragraph's text into 100 current measurement units.");
});
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
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) => {
// Insert the sentence, then adjust the formatting.
// Note that replace affects the calling object, in this case the entire document body.
// A similar method can also be used at the range level.
const sentence: Word.Range = context.document.body.insertText(
"This is some formatted text!",
"Replace"
);
sentence.font.set({
name: "Courier New",
bold: true,
size: 18
});
await context.sync();
});
footnotes
Gets the collection of footnotes in the range.
readonly footnotes: Word.NoteItemCollection;
Property Value
Remarks
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: Word.NoteItemCollection = context.document.getSelection().footnotes;
footnotes.load("length");
await context.sync();
console.log(`Number of footnotes in the selected range: ${footnotes.items.length}`);
});
frames
Gets a FrameCollection object that represents all the frames in the range.
readonly frames: Word.FrameCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml
// Reads the text and dimensions of frames in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const frames: Word.FrameCollection = bodyRange.frames;
frames.load("items/width,items/height,items/range/text");
await context.sync();
console.log(`Frames found: ${frames.items.length}`);
frames.items.forEach((frame: Word.Frame) => {
console.log({ width: frame.width, height: frame.height, text: frame.range.text });
});
});
grammarChecked
Specifies if a grammar check has been run on the range or document.
grammarChecked: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Marks the first paragraph as needing another grammar check.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.grammarChecked = false;
await context.sync();
console.log("Reset the English paragraph's grammar-checked flag. Get language and proofing settings to inspect it.");
});
hasNoProofing
Specifies the proofing status (spelling and grammar checking) of the range.
hasNoProofing: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Disables spelling and grammar checking for the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.hasNoProofing = true;
await context.sync();
console.log("Disabled spelling and grammar checking for the English paragraph. Get language and proofing settings to verify it.");
});
highlightColorIndex
Specifies the highlight color for the range.
readonly highlightColorIndex: Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor";
Property Value
Word.ColorIndex | "Auto" | "Black" | "Blue" | "Turquoise" | "BrightGreen" | "Pink" | "Red" | "Yellow" | "White" | "DarkBlue" | "Teal" | "Green" | "Violet" | "DarkRed" | "DarkYellow" | "Gray50" | "Gray25" | "ClassicRed" | "ClassicBlue" | "ByAuthor"
Remarks
horizontalInVertical
Specifies the formatting for horizontal text set within vertical text.
horizontalInVertical: Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine";
Property Value
Word.HorizontalInVerticalType | "None" | "FitInLine" | "ResizeLine"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml
// Keeps the first paragraph's characters horizontal within vertical text.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const horizontalLayout: Word.HorizontalInVerticalType = Word.HorizontalInVerticalType.fitInLine;
paragraphRange.horizontalInVertical = horizontalLayout;
await context.sync();
console.log("Enabled horizontal-in-vertical layout on the first paragraph. Get layout settings to verify it.");
});
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.
hyperlink: string;
Property Value
string
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Links the first paragraph's text to the Word add-in documentation.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.hyperlink = "https://learn.microsoft.com/office/dev/add-ins/word/";
await context.sync();
console.log("Linked the summary text to the Word add-in documentation.");
});
hyperlinks
Returns a HyperlinkCollection object that represents all the hyperlinks in the range.
readonly hyperlinks: Word.HyperlinkCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml
// Reads hyperlink objects and their destinations in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const hyperlinks: Word.HyperlinkCollection = bodyRange.hyperlinks;
hyperlinks.load("items/address,items/range/text");
await context.sync();
console.log(`Hyperlinks found: ${hyperlinks.items.length}`);
hyperlinks.items.forEach((hyperlink: Word.Hyperlink) => {
console.log({ address: hyperlink.address, text: hyperlink.range.text });
});
});
id
Specifies the ID for the range.
id: string;
Property Value
string
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml
// Reads the range's character positions and the story containing it.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.load("id,start,end,storyLength,storyType,isEndOfRowMark,isTextVisibleOnScreen");
await context.sync();
console.log("First paragraph's position and story:", {
id: paragraphRange.id,
start: paragraphRange.start,
end: paragraphRange.end,
storyLength: paragraphRange.storyLength,
storyType: paragraphRange.storyType,
isEndOfRowMark: paragraphRange.isEndOfRowMark,
isTextVisibleOnScreen: paragraphRange.isTextVisibleOnScreen
});
});
inlinePictures
Gets the collection of InlinePicture objects in the range.
readonly inlinePictures: Word.InlinePictureCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Reads the dimensions of inline pictures in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const pictures: Word.InlinePictureCollection = bodyRange.inlinePictures;
pictures.load("items/width,items/height");
await context.sync();
console.log(`Inline pictures found: ${pictures.items.length}`);
pictures.items.forEach((picture: Word.InlinePicture) => console.log({ width: picture.width, height: picture.height }));
});
isEmpty
Checks whether the range length is zero.
readonly isEmpty: boolean;
Property Value
boolean
Remarks
isEndOfRowMark
Gets if the range is collapsed and is located at the end-of-row mark in a table.
readonly isEndOfRowMark: boolean;
Property Value
boolean
Remarks
isTextVisibleOnScreen
Gets whether the text in the range is visible on the screen.
readonly isTextVisibleOnScreen: boolean;
Property Value
boolean
Remarks
italic
Specifies if the font or range is formatted as italic.
readonly italic: boolean;
Property Value
boolean
Remarks
italicBidirectional
Specifies if the font or range is formatted as italic (right-to-left languages).
readonly italicBidirectional: boolean;
Property Value
boolean
Remarks
kana
Specifies whether the range of Japanese language text is hiragana or katakana.
kana: Word.Kana | "Katakana" | "Hiragana";
Property Value
Word.Kana | "Katakana" | "Hiragana"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/convert-japanese-kana-desktop.yaml
// Converts the sample paragraph's Japanese katakana text to hiragana.
await Word.run(async (context) => {
const japaneseRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const kana: Word.Kana = Word.Kana.hiragana;
japaneseRange.kana = kana;
await context.sync();
console.log("Converted the Japanese paragraph's text to hiragana.");
});
languageDetected
Specifies whether Microsoft Word has detected the language of the text in the range.
languageDetected: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Marks the first paragraph's language as not yet detected.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.languageDetected = false;
await context.sync();
console.log("Reset the English paragraph's language-detected flag. Get language and proofing settings to inspect it.");
});
languageId
Specifies a LanguageId value that represents the language for the range.
languageId: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";
Property Value
Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Sets the first paragraph's proofing language to US English.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const language: Word.LanguageId = Word.LanguageId.englishUS;
paragraphRange.languageId = language;
await context.sync();
console.log("Set the English paragraph's proofing language to US English.");
});
languageIdFarEast
Specifies an East Asian language for the range.
languageIdFarEast: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";
Property Value
Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Sets the Japanese paragraph's East Asian language.
await Word.run(async (context) => {
const japaneseRange: Word.Range = context.document.body.paragraphs.getLast().getRange(Word.RangeLocation.content);
const language: Word.LanguageId = Word.LanguageId.japanese;
japaneseRange.languageIdFarEast = language;
await context.sync();
console.log("Set the Japanese paragraph's East Asian language to Japanese.");
});
languageIdOther
Specifies a language for the range that isn't classified as an East Asian language.
languageIdOther: Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu";
Property Value
Word.LanguageId | "Afrikaans" | "Albanian" | "Amharic" | "Arabic" | "ArabicAlgeria" | "ArabicBahrain" | "ArabicEgypt" | "ArabicIraq" | "ArabicJordan" | "ArabicKuwait" | "ArabicLebanon" | "ArabicLibya" | "ArabicMorocco" | "ArabicOman" | "ArabicQatar" | "ArabicSyria" | "ArabicTunisia" | "ArabicUAE" | "ArabicYemen" | "Armenian" | "Assamese" | "AzeriCyrillic" | "AzeriLatin" | "Basque" | "BelgianDutch" | "BelgianFrench" | "Bengali" | "Bulgarian" | "Burmese" | "Belarusian" | "Catalan" | "Cherokee" | "ChineseHongKongSAR" | "ChineseMacaoSAR" | "ChineseSingapore" | "Croatian" | "Czech" | "Danish" | "Divehi" | "Dutch" | "Edo" | "EnglishAUS" | "EnglishBelize" | "EnglishCanadian" | "EnglishCaribbean" | "EnglishIndonesia" | "EnglishIreland" | "EnglishJamaica" | "EnglishNewZealand" | "EnglishPhilippines" | "EnglishSouthAfrica" | "EnglishTrinidadTobago" | "EnglishUK" | "EnglishUS" | "EnglishZimbabwe" | "Estonian" | "Faeroese" | "Filipino" | "Finnish" | "French" | "FrenchCameroon" | "FrenchCanadian" | "FrenchCongoDRC" | "FrenchCotedIvoire" | "FrenchHaiti" | "FrenchLuxembourg" | "FrenchMali" | "FrenchMonaco" | "FrenchMorocco" | "FrenchReunion" | "FrenchSenegal" | "FrenchWestIndies" | "FrisianNetherlands" | "Fulfulde" | "GaelicIreland" | "GaelicScotland" | "Galician" | "Georgian" | "German" | "GermanAustria" | "GermanLiechtenstein" | "GermanLuxembourg" | "Greek" | "Guarani" | "Gujarati" | "Hausa" | "Hawaiian" | "Hebrew" | "Hindi" | "Hungarian" | "Ibibio" | "Icelandic" | "Igbo" | "Indonesian" | "Inuktitut" | "Italian" | "Japanese" | "Kannada" | "Kanuri" | "Kashmiri" | "Kazakh" | "Khmer" | "Kirghiz" | "Konkani" | "Korean" | "Kyrgyz" | "LanguageNone" | "Lao" | "Latin" | "Latvian" | "Lithuanian" | "MacedonianFYROM" | "Malayalam" | "MalayBruneiDarussalam" | "Malaysian" | "Maltese" | "Manipuri" | "Marathi" | "MexicanSpanish" | "Mongolian" | "Nepali" | "NoProofing" | "NorwegianBokmol" | "NorwegianNynorsk" | "Oriya" | "Oromo" | "Pashto" | "Persian" | "Polish" | "Portuguese" | "PortugueseBrazil" | "Punjabi" | "RhaetoRomanic" | "Romanian" | "RomanianMoldova" | "Russian" | "RussianMoldova" | "SamiLappish" | "Sanskrit" | "SerbianCyrillic" | "SerbianLatin" | "Sesotho" | "SimplifiedChinese" | "Sindhi" | "SindhiPakistan" | "Sinhalese" | "Slovak" | "Slovenian" | "Somali" | "Sorbian" | "Spanish" | "SpanishArgentina" | "SpanishBolivia" | "SpanishChile" | "SpanishColombia" | "SpanishCostaRica" | "SpanishDominicanRepublic" | "SpanishEcuador" | "SpanishElSalvador" | "SpanishGuatemala" | "SpanishHonduras" | "SpanishModernSort" | "SpanishNicaragua" | "SpanishPanama" | "SpanishParaguay" | "SpanishPeru" | "SpanishPuertoRico" | "SpanishUruguay" | "SpanishVenezuela" | "Sutu" | "Swahili" | "Swedish" | "SwedishFinland" | "SwissFrench" | "SwissGerman" | "SwissItalian" | "Syriac" | "Tajik" | "Tamazight" | "TamazightLatin" | "Tamil" | "Tatar" | "Telugu" | "Thai" | "Tibetan" | "TigrignaEritrea" | "TigrignaEthiopic" | "TraditionalChinese" | "Tsonga" | "Tswana" | "Turkish" | "Turkmen" | "Ukrainian" | "Urdu" | "UzbekCyrillic" | "UzbekLatin" | "Venda" | "Vietnamese" | "Welsh" | "Xhosa" | "Yi" | "Yiddish" | "Yoruba" | "Zulu"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Sets the first paragraph's non-East-Asian language to US English.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const language: Word.LanguageId = Word.LanguageId.englishUS;
paragraphRange.languageIdOther = language;
await context.sync();
console.log("Set the English paragraph's non-East-Asian language to US English.");
});
listFormat
Returns a ListFormat object that represents all the list formatting characteristics of the range.
readonly listFormat: Word.ListFormat;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/20-lists/format-list-range.yaml
// Gets the range covering the entire body and reads list formatting properties.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const listFormat: Word.ListFormat = bodyRange.listFormat;
listFormat.load("isSingleList, listType, listLevelNumber, listString, listValue");
await context.sync();
console.log("List format info for the body range:");
console.log(`- Is single list: ${listFormat.isSingleList}`);
console.log(`- List type: ${listFormat.listType}`);
console.log(`- List level number (first paragraph): ${listFormat.listLevelNumber}`);
console.log(`- List string (first paragraph): "${listFormat.listString}"`);
console.log(`- List value (first paragraph): ${listFormat.listValue}`);
});
lists
Gets the collection of List objects in the range.
readonly lists: Word.ListCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Reads the identifiers of lists in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const lists: Word.ListCollection = bodyRange.lists;
lists.load("items/id");
await context.sync();
console.log(`Lists found: ${lists.items.length}`);
lists.items.forEach((list: Word.List) => console.log(`List ID: ${list.id}`));
});
pages
Gets the collection of pages in the range.
readonly pages: Word.PageCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/36-pages/get-pages.yaml
// Reads the index and text of each page intersecting the selection.
await Word.run(async (context) => {
const selectedRange: Word.Range = context.document.getSelection();
const pages: Word.PageCollection = selectedRange.pages;
pages.load("items/index");
await context.sync();
console.log(`Pages in the selection: ${pages.items.length}`);
const pageRanges: Word.Range[] = [];
pages.items.forEach((page: Word.Page) => {
const pageRange: Word.Range = page.getRange(Word.RangeLocation.whole);
pageRange.load("text");
pageRanges.push(pageRange);
});
await context.sync();
for (let i = 0; i < pages.items.length; i++) {
console.log(`Page ${pages.items[i].index} text: ${pageRanges[i].text}`);
}
});
paragraphs
Gets the collection of Paragraph objects in the range.
readonly paragraphs: Word.ParagraphCollection;
Property Value
Remarks
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.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-annotations.yaml
// Accepts the first annotation found in the selected paragraph.
await Word.run(async (context) => {
const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
annotations.load("id,state,critiqueAnnotation");
await context.sync();
for (let i = 0; i < annotations.items.length; i++) {
const annotation: Word.Annotation = annotations.items[i];
if (annotation.state === Word.AnnotationState.created) {
console.log(`Accepting ID ${annotation.id}...`);
annotation.critiqueAnnotation.accept();
await context.sync();
break;
}
}
});
parentBody
Gets the parent body of the range.
readonly parentBody: Word.Body;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/insert-section-breaks.yaml
// Gets the section after the current selection when another section is expected.
await Word.run(async (context) => {
const selection: Word.Range = context.document.getSelection();
const selectedBody: Word.Body = selection.parentBody;
const selectedSection: Word.Section = selectedBody.parentSection;
const nextSection: Word.Section = selectedSection.getNext();
const nextSectionBody: Word.Body = nextSection.body;
nextSectionBody.load("text");
await context.sync();
console.log(`Next section text: ${nextSectionBody.text}`);
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-checkbox-content-control.yaml
// Toggles the isChecked property of the first checkbox content control found in the selection.
await Word.run(async (context) => {
const selectedRange: Word.Range = context.document.getSelection();
let selectedContentControl = selectedRange
.getContentControls({
types: [Word.ContentControlType.checkBox]
})
.getFirstOrNullObject();
selectedContentControl.load("id,checkboxContentControl/isChecked");
await context.sync();
if (selectedContentControl.isNullObject) {
const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
parentContentControl.load("id,type,checkboxContentControl/isChecked");
await context.sync();
if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
console.warn("No checkbox content control is currently selected.");
return;
} else {
selectedContentControl = parentContentControl;
}
}
const isCheckedBefore = selectedContentControl.checkboxContentControl.isChecked;
console.log("isChecked state before:", `id: ${selectedContentControl.id} ... isChecked: ${isCheckedBefore}`);
selectedContentControl.checkboxContentControl.isChecked = !isCheckedBefore;
selectedContentControl.load("id,checkboxContentControl/isChecked");
await context.sync();
console.log(
"isChecked state after:",
`id: ${selectedContentControl.id} ... isChecked: ${selectedContentControl.checkboxContentControl.isChecked}`
);
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-date-picker-content-control.yaml
// Deletes the first date picker content control found in the selection.
await Word.run(async (context) => {
// First, look if the selection contains a date picker content control.
const selectedRange: Word.Range = context.document.getSelection();
let selectedContentControl = selectedRange
.getContentControls({
types: [Word.ContentControlType.datePicker]
})
.getFirstOrNullObject();
selectedContentControl.load("id");
await context.sync();
// The selection doesn't contain a date picker, but the cursor might be inside one.
// Check if the selection's parent content control is a date picker.
if (selectedContentControl.isNullObject) {
const parentContentControl: Word.ContentControl = selectedRange.parentContentControlOrNullObject;
parentContentControl.load("id,type");
await context.sync();
if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.datePicker) {
console.warn("Please select a date picker content control before selecting Delete.");
return;
}
selectedContentControl = parentContentControl;
}
console.log(`About to delete date picker content control with ID: ${selectedContentControl.id}`);
selectedContentControl.delete(false);
await context.sync();
console.log("Deleted date picker content control.");
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Reads the table containing the first table cell's range.
await Word.run(async (context) => {
const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
const parentTable: Word.Table = cellRange.parentTable;
parentTable.load("rowCount,values");
await context.sync();
console.log("Parent table:", { rowCount: parentTable.rowCount, values: parentTable.values });
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Reads the cell containing the first table cell's range.
await Word.run(async (context) => {
const cellRange: Word.Range = context.document.body.tables.getFirst().getCell(0, 0).body.getRange();
const parentCell: Word.TableCell = cellRange.parentTableCell;
parentCell.load("rowIndex,cellIndex,value");
await context.sync();
console.log("Parent cell:", { rowIndex: parentCell.rowIndex, cellIndex: parentCell.cellIndex, value: parentCell.value });
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Checks whether the first paragraph is inside a table cell.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const parentCell: Word.TableCell = paragraphRange.parentTableCellOrNullObject;
parentCell.load("value");
await context.sync();
if (parentCell.isNullObject) {
console.warn("The first paragraph is not inside a table cell.");
return;
}
console.log(`Parent cell text: ${parentCell.value}`);
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Checks whether the first paragraph is inside a table.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const parentTable: Word.Table = paragraphRange.parentTableOrNullObject;
parentTable.load("rowCount");
await context.sync();
if (parentTable.isNullObject) {
console.warn("The first paragraph is not inside a table.");
return;
}
console.log(`Parent table rows: ${parentTable.rowCount}`);
});
revisions
Gets the collection of revisions that represents the tracked changes in the range.
readonly revisions: Word.RevisionCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-tracked-changes.yaml
// Reads revision metadata for the first paragraph on desktop Word.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const revisions: Word.RevisionCollection = paragraphRange.revisions;
revisions.load("items/author,items/date,items/type,items/index,items/formatDescription");
await context.sync();
console.log(`Revisions in the first paragraph: ${revisions.items.length}`);
revisions.items.forEach((revision: Word.Revision) => {
console.log("Revision properties:", {
author: revision.author,
date: revision.date,
type: revision.type,
index: revision.index,
formatDescription: revision.formatDescription,
});
});
});
sections
Gets the collection of sections in the range.
readonly sections: Word.SectionCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-layout-desktop.yaml
// Reads the text of sections intersecting the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const sections: Word.SectionCollection = bodyRange.sections;
sections.load("items/body/text");
await context.sync();
console.log(`Sections found: ${sections.items.length}`);
sections.items.forEach((section: Word.Section) => console.log(section.body.text));
});
shading
Returns a ShadingUniversal object that refers to the shading formatting for the range.
readonly shading: Word.ShadingUniversal;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/range-borders-and-shading-desktop.yaml
// Adds a pale blue background to the first paragraph's text.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const shading: Word.ShadingUniversal = paragraphRange.shading;
shading.backgroundPatternColor = "#DDEBF7";
await context.sync();
console.log("Applied pale blue shading.");
});
shapes
Gets the collection of Shape objects anchored in the range, including both inline and floating shapes. Currently, only the following shapes are supported: text boxes, geometric shapes, groups, pictures, and canvases.
readonly shapes: Word.ShapeCollection;
Property Value
Remarks
Important: Be aware that with time, additional types of shapes may be supported. Therefore, your add-in should request and handle specific types of shapes.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-inspect-floating-pictures-desktop.yaml
// Reads shapes anchored within the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const shapes: Word.ShapeCollection = paragraphRange.shapes;
shapes.load("items/name,items/type,items/width,items/height");
await context.sync();
console.log(`Shapes anchored in the first paragraph: ${shapes.items.length}`);
shapes.items.forEach((shape: Word.Shape) => {
console.log("Anchored shape:", { name: shape.name, type: shape.type, width: shape.width, height: shape.height });
});
});
showAll
Specifies if all nonprinting characters (such as hidden text, tab marks, space marks, and paragraph marks) are displayed.
showAll: boolean;
Property Value
boolean
Remarks
spellingChecked
Specifies if spelling has been checked throughout the range or document.
spellingChecked: boolean;
Property Value
boolean
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/manage-language-and-proofing-desktop.yaml
// Marks the first paragraph as needing another spelling check.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.spellingChecked = false;
await context.sync();
console.log("Reset the English paragraph's spelling-checked flag. Get language and proofing settings to inspect it.");
});
start
Specifies the starting character position of the range.
start: number;
Property Value
number
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-and-adjust-range-boundaries-desktop.yaml
// Selects the first paragraph's text except its first character.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.load("start,end");
await context.sync();
if (paragraphRange.start === paragraphRange.end) {
console.warn("The paragraph is empty. Run Set up again.");
return;
}
paragraphRange.start = paragraphRange.start + 1;
paragraphRange.select();
await context.sync();
console.log("Selected the range with its starting position advanced by one character.");
});
storyLength
Gets the number of characters in the story that contains the range.
readonly storyLength: number;
Property Value
number
Remarks
storyType
Gets the story type for the range.
readonly storyType: Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice";
Property Value
Word.StoryType | "MainText" | "Footnotes" | "Endnotes" | "Comments" | "TextFrame" | "EvenPagesHeader" | "PrimaryHeader" | "EvenPagesFooter" | "PrimaryFooter" | "FirstPageHeader" | "FirstPageFooter" | "FootnoteSeparator" | "FootnoteContinuationSeparator" | "FootnoteContinuationNotice" | "EndnoteSeparator" | "EndnoteContinuationSeparator" | "EndnoteContinuationNotice"
Remarks
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Applies the sample's custom paragraph style to the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
paragraphRange.style = "RangeSampleStyle";
await context.sync();
console.log("Applied the sample's custom style.");
});
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
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: Word.Range = 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();
});
tableColumns
Gets a TableColumnCollection object that represents all the table columns in the range.
readonly tableColumns: Word.TableColumnCollection;
Property Value
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/40-tables/manage-table-rows-columns-cells.yaml
// Gets properties of the first column in the sample table.
await Word.run(async (context) => {
const firstTable: Word.Table = context.document.body.tables.getFirst();
const tableRange: Word.Range = firstTable.getRange();
const tableColumns: Word.TableColumnCollection = tableRange.tableColumns;
tableColumns.load("items/columnIndex,items/isFirst,items/isLast,items/width");
await context.sync();
const firstColumn: Word.TableColumn = tableColumns.items[0];
console.log(
"First table column:",
`- Index: ${firstColumn.columnIndex}`,
`- Is first: ${firstColumn.isFirst}`,
`- Is last: ${firstColumn.isLast}`,
`- Width: ${firstColumn.width} points`
);
});
tables
Gets the collection of Table objects in the range.
readonly tables: Word.TableCollection;
Property Value
Remarks
text
Gets the text of the range.
readonly text: string;
Property Value
string
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/05-coauthoring/get-coauthoring-updates.yaml
// Gets the ranges affected by the most recent coauthoring updates merged into the document.
await Word.run(async (context) => {
const updates: Word.CoauthoringUpdateCollection = context.document.coauthoring.updates;
updates.load("items/range");
await context.sync();
if (updates.items.length === 0) {
console.log("No recent coauthoring updates found.");
return;
}
console.log(`Found ${updates.items.length} recent update(s).`);
const ranges = updates.items.map((u) => u.range);
ranges.forEach((r) => r.load("text"));
await context.sync();
ranges.forEach((range, i) => {
console.log(` Update ${i + 1}: "${range.text}"`);
});
});
twoLinesInOne
Specifies whether Microsoft Word sets two lines of text in one and specifies the characters that enclose the text, if any.
twoLinesInOne: Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets";
Property Value
Word.TwoLinesInOneType | "None" | "NoBrackets" | "Parentheses" | "SquareBrackets" | "AngleBrackets" | "CurlyBrackets"
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/28-formatting/apply-character-layout-desktop.yaml
// Displays the first paragraph's text as two lines enclosed in parentheses.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const twoLineLayout: Word.TwoLinesInOneType = Word.TwoLinesInOneType.parentheses;
paragraphRange.twoLinesInOne = twoLineLayout;
await context.sync();
console.log("Applied two-line text with parentheses to the first paragraph.");
});
underline
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.
Specifies the type of underline applied to the range.
readonly underline: Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble";
Property Value
Word.UnderlineType | "Mixed" | "None" | "Hidden" | "DotLine" | "Single" | "Word" | "Double" | "Thick" | "Dotted" | "DottedHeavy" | "DashLine" | "DashLineHeavy" | "DashLineLong" | "DashLineLongHeavy" | "DotDashLine" | "DotDashLineHeavy" | "TwoDotDashLine" | "TwoDotDashLineHeavy" | "Wave" | "WaveHeavy" | "WaveDouble"
Remarks
API set: WordApi BETA (PREVIEW ONLY)
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/99-preview-apis/read-range-underline.yaml
// Reads the underline applied to the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.load("underline");
await context.sync();
const singleUnderline: Word.UnderlineType = Word.UnderlineType.single;
console.log(`Underline type: ${paragraphRange.underline}`);
console.log(`Has a single underline: ${paragraphRange.underline === singleUnderline}`);
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Removes the first paragraph's text while preserving the paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.clear();
await context.sync();
console.log("Cleared the summary text. The paragraph remains.");
});
compareLocationWith(range)
Compares this range's location with another range's location.
compareLocationWith(range: Word.Range): OfficeExtension.ClientResult<Word.LocationRelation>;
Parameters
- range
- Word.Range
The range to compare with this range.
Returns
Remarks
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: Word.ParagraphCollection = context.document.body.paragraphs;
paragraphs.load("items");
await context.sync();
const firstParagraphAsRange: Word.Range = paragraphs.items[0].getRange();
const secondParagraphAsRange: Word.Range = paragraphs.items[1].getRange();
const comparedLocation: OfficeExtension.ClientResult<Word.LocationRelation> =
firstParagraphAsRange.compareLocationWith(secondParagraphAsRange);
await context.sync();
const locationValue: Word.LocationRelation = comparedLocation.value;
console.log(`Location of the first paragraph in relation to the second paragraph: ${locationValue}`);
});
delete()
Deletes the range and its content from the document.
delete(): void;
Returns
void
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Deletes the first paragraph range, including its paragraph mark.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
paragraphRange.delete();
await context.sync();
console.log("Deleted the first paragraph range.");
});
detectLanguage()
Analyzes the range text to determine the language that it's written in.
detectLanguage(): OfficeExtension.ClientResult<boolean>;
Returns
OfficeExtension.ClientResult<boolean>
Remarks
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 don't have a union.
expandTo(range: Word.Range): Word.Range;
Parameters
- range
- Word.Range
Another range.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml
// Gets the text spanning the first two paragraphs.
await Word.run(async (context) => {
const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const secondRange: Word.Range = context.document.body.paragraphs.getFirst().getNext().getRange();
const expandedRange: Word.Range = firstRange.expandTo(secondRange);
expandedRange.load("text");
await context.sync();
console.log(`Expanded text: ${expandedRange.text}`);
});
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
Another range.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml
// Expands to the selection when both ranges belong to the same story.
await Word.run(async (context) => {
const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const selection: Word.Range = context.document.getSelection();
const expandedRange: Word.Range = firstRange.expandToOrNullObject(selection);
expandedRange.load("text");
await context.sync();
if (expandedRange.isNullObject) {
console.warn("The ranges cannot be combined. Select text in the main document body.");
return;
}
console.log(`Expanded text: ${expandedRange.text}`);
});
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
OfficeExtension.ClientResult<string[]>
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml
// Gets the names of bookmarks within or overlapping the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const bookmarkNames: OfficeExtension.ClientResult<string[]> = paragraphRange.getBookmarks(false, true);
await context.sync();
console.log("Bookmark names:", bookmarkNames.value);
});
getComments()
Gets comments associated with the range.
getComments(): Word.CommentCollection;
Returns
A CommentCollection object that contains all the comments associated with the range.
Remarks
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: Word.CommentCollection = context.document.getSelection().getComments();
// Load objects to log in the console.
comments.load();
await context.sync();
console.log("Comments:", 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
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.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-checkbox-content-control.yaml
// Deletes the first checkbox content control found in the selection.
await Word.run(async (context) => {
const selectedRange: Word.Range = context.document.getSelection();
let selectedContentControl = selectedRange
.getContentControls({
types: [Word.ContentControlType.checkBox]
})
.getFirstOrNullObject();
selectedContentControl.load("id");
await context.sync();
if (selectedContentControl.isNullObject) {
const parentContentControl: Word.ContentControl = selectedRange.parentContentControl;
parentContentControl.load("id,type");
await context.sync();
if (parentContentControl.isNullObject || parentContentControl.type !== Word.ContentControlType.checkBox) {
console.warn("No checkbox content control is currently selected.");
return;
} else {
selectedContentControl = parentContentControl;
}
}
console.log(`About to delete checkbox content control with id: ${selectedContentControl.id}`);
selectedContentControl.delete(false);
await context.sync();
console.log("Deleted checkbox content control.");
});
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
OfficeExtension.ClientResult<string>
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml
// Reads an HTML representation of the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const html: OfficeExtension.ClientResult<string> = paragraphRange.getHtml();
await context.sync();
console.log(`Range HTML: ${html.value}`);
});
getHyperlinkRanges()
Gets hyperlink child ranges within the range.
getHyperlinkRanges(): Word.RangeCollection;
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Reads the text and destinations of hyperlinks in the document body range.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const hyperlinkRanges: Word.RangeCollection = bodyRange.getHyperlinkRanges();
hyperlinkRanges.load("items/text,items/hyperlink");
await context.sync();
console.log(`Hyperlinks found: ${hyperlinkRanges.items.length}`);
hyperlinkRanges.items.forEach((hyperlinkRange: Word.Range) => {
console.log({ text: hyperlinkRange.text, hyperlink: hyperlinkRange.hyperlink });
});
});
getNextTextRange(endingMarks, trimSpacing)
Gets the next text range by using punctuation marks and 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[]
The punctuation marks and 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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml
// Gets the sentence following the first sentence in the document.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const firstSentence: Word.Range = paragraphRange.getTextRanges(["?", "."], true).getFirst();
const nextSentence: Word.Range = firstSentence.getNextTextRange(["?", "."], true);
nextSentence.load("text");
await context.sync();
console.log(`Next sentence: ${nextSentence.text}`);
});
getNextTextRangeOrNullObject(endingMarks, trimSpacing)
Gets the next text range by using punctuation marks and 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[]
The punctuation marks and 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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml
// Checks for a sentence after the end of the document without throwing.
await Word.run(async (context) => {
const endRange: Word.Range = context.document.body.getRange(Word.RangeLocation.end);
const nextSentence: Word.Range = endRange.getNextTextRangeOrNullObject([".", "?"], true);
nextSentence.load("text");
await context.sync();
if (nextSentence.isNullObject) {
console.warn("There is no sentence after the end of the document.");
return;
}
console.log(`Next sentence: ${nextSentence.text}`);
});
getOoxml()
Gets the OOXML representation of the Range object.
getOoxml(): OfficeExtension.ClientResult<string>;
Returns
OfficeExtension.ClientResult<string>
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml
// Reads the OOXML representation of the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const ooxml: OfficeExtension.ClientResult<string> = paragraphRange.getOoxml();
await context.sync();
console.log(`Range OOXML: ${ooxml.value}`);
});
getRange(rangeLocation)
Clones the Range object, 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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-dropdown-list-content-control.yaml
// Places a dropdown list content control at the end of the selection.
await Word.run(async (context) => {
let selection = context.document.getSelection();
selection.getRange(Word.RangeLocation.end).insertContentControl(Word.ContentControlType.dropDownList);
await context.sync();
console.log("Dropdown list content control inserted at the end of the selection.");
});
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
OfficeExtension.ClientResult<string>
Remarks
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: Word.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):", before.value, "Reviewed text (after):", after.value);
});
getReviewedText(changeTrackingVersion)
Gets reviewed text based on ChangeTrackingVersion selection.
getReviewedText(changeTrackingVersion?: "Original" | "Current"): OfficeExtension.ClientResult<string>;
Parameters
- changeTrackingVersion
-
"Original" | "Current"
Optional. The value must be original or current. The default is current.
Returns
OfficeExtension.ClientResult<string>
Remarks
getTextRanges(endingMarks, trimSpacing)
Gets the text child ranges in the range by using punctuation marks and other ending marks.
getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection;
Parameters
- endingMarks
-
string[]
The punctuation marks and 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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/25-paragraph/get-paragraph-on-insertion-point.yaml
// Gets complete sentences from the insertion point to the end of its paragraph.
await Word.run(async (context) => {
const selection: Word.Range = context.document.getSelection();
const sentences: Word.RangeCollection = selection.getTextRanges(["."], false);
sentences.load("$none");
await context.sync();
const firstSentence: Word.Range = sentences.items[0];
const paragraphEnd: Word.Range = selection.paragraphs.getFirst().getRange(Word.RangeLocation.end);
const remainingRange: Word.Range = firstSentence.expandTo(paragraphEnd);
const sentencesToTheEndOfParagraph: Word.RangeCollection = remainingRange.getTextRanges(["."], false);
sentencesToTheEndOfParagraph.load("text");
await context.sync();
console.log("Sentences from the current sentence to the paragraph end:");
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-tracked-changes.yaml
// Gets the tracked changes inside the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const trackedChanges: Word.TrackedChangeCollection = paragraphRange.getTrackedChanges();
trackedChanges.load("items/author,items/text,items/type");
await context.sync();
console.log(`Tracked changes in the first paragraph: ${trackedChanges.items.length}`);
trackedChanges.items.forEach((change: Word.TrackedChange) => {
console.log({ author: change.author, text: change.text, type: change.type });
});
});
highlight()
Highlights the range temporarily without changing document content. To highlight the text permanently, set the range's font.highlightColor.
highlight(): void;
Returns
void
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml
// Temporarily highlights the final paragraph without changing its formatting.
await Word.run(async (context) => {
const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
lastRange.highlight();
await context.sync();
console.log("Temporarily highlighted the final paragraph.");
});
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
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
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.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/manage-range-bookmarks.yaml
// Names the first paragraph range, replacing any existing bookmark with this name.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
paragraphRange.insertBookmark("RangeSampleSummary");
await context.sync();
console.log("Inserted the RangeSampleSummary bookmark. Get bookmark names to verify it.");
});
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"
The break type to add.
Returns
void
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Inserts a page break after the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
paragraphRange.insertBreak(Word.BreakType.page, Word.InsertLocation.after);
await context.sync();
console.log("Inserted a page break after the summary.");
});
insertCanvas(insertShapeOptions)
Inserts a floating canvas in front of text with its anchor at the beginning of the range.
insertCanvas(insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;
Parameters
- insertShapeOptions
- Word.InsertShapeOptions
Optional. The location and size of the canvas. The default location and size is (0, 0, 300, 200).
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-canvases.yaml
await Word.run(async (context) => {
// Inserts a canvas in the document.
const canvasShape: Word.Shape = context.document.getSelection().insertCanvas();
canvasShape.load();
await context.sync();
canvasShape.select();
console.log("Inserted canvas:", canvasShape);
const canvas: Word.Canvas = canvasShape.canvas;
canvas.load("shape,shapes");
await context.sync();
console.log("Canvas object:", canvas);
});
insertComment(commentText)
Insert a comment on the range.
insertComment(commentText: string): Word.Comment;
Parameters
- commentText
-
string
The comment text to be inserted.
Returns
The Comment object that was inserted.
Remarks
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 = (document.getElementById("comment-text") as HTMLInputElement).value;
const comment: Word.Comment = context.document.getSelection().insertComment(text);
// Load object to log in the console.
comment.load();
await context.sync();
console.log("Comment inserted:", comment);
});
insertContentControl(contentControlType)
Wraps the Range object with a content control.
insertContentControl(contentControlType?: Word.ContentControlType.richText | Word.ContentControlType.plainText | Word.ContentControlType.checkBox | Word.ContentControlType.dropDownList | Word.ContentControlType.comboBox | Word.ContentControlType.buildingBlockGallery | Word.ContentControlType.datePicker | Word.ContentControlType.repeatingSection | Word.ContentControlType.picture | Word.ContentControlType.group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"): Word.ContentControl;
Parameters
- contentControlType
-
richText | plainText | checkBox | dropDownList | comboBox | buildingBlockGallery | datePicker | repeatingSection | picture | group | "RichText" | "PlainText" | "CheckBox" | "DropDownList" | "ComboBox" | "BuildingBlockGallery" | "DatePicker" | "RepeatingSection" | "Picture" | "Group"
Optional. Content control type to insert. Must be richText, plainText, checkBox, dropDownList, comboBox, buildingBlockGallery, datePicker, repeatingSection, picture, or group. The default is richText.
Returns
Remarks
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. dropDownList and comboBox support was added in WordApi 1.9. Support for buildingBlockGallery, datePicker, group, picture, and repeatingSection was added in WordApiDesktop 1.3.
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: Word.RangeCollection = context.document.body.search("Contractor");
results.load("font/bold");
// Check to make sure these content controls haven't been added yet.
const customerContentControls: Word.ContentControlCollection = 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: Word.ContentControl = 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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/50-document/manage-footnotes.yaml
// Adds an endnote to the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const endnote: Word.NoteItem = paragraphRange.insertEndnote("Source: the sample document.");
await context.sync();
console.log("Inserted an endnote. Its text appears at the end of the document.");
});
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"
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 value. 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
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, fields are mainly read-only. To learn more, see Use fields in your Word add-in.
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) => {
const range: Word.Range = context.document.getSelection().getRange();
const field: Word.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, "Result of the field: " + JSON.stringify(field.result));
}
});
insertField(insertLocation, fieldType, text, removeFormatting)
Inserts a field at the specified location.
insertField(insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After", fieldType?: "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"
The location relative to the range where the field will be inserted. The value must be replace, start, end, before, or after.
- fieldType
-
"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 value. 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
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, fields are mainly read-only. To learn more, see Use fields in your Word add-in.
insertFileFromBase64(base64File, insertLocation)
Inserts a document at the specified location. The maximum size of the document being inserted is 4 MB.
insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"): Word.Range;
Parameters
- base64File
-
string
The Base64-encoded content of a .docx file.
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
The value must be replace, start, end, before, or after.
Returns
Remarks
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.
Insertion isn't supported if the document being inserted contains linked or external content. If it does, this method returns an InvalidArgument error.
Document settings aren't preserved when inserting a document.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml
// Replaces the first paragraph with the contents of a small embedded DOCX file.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
// The DOCX contains one paragraph: "Imported project update."
const base64File: string = "UEsDBBQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH2QuQ7CMAyGX6XKiqgRAwOiLMAKDLyAlbptRC7FLsfbk3INCBjt//gsLw7XSFxcnPVcqU4kzgFYd+SQyxDJZ6UJyaHkMbUQUR+xJZhOJjPQwQt5GcvQoZaLNTXYWyk2l7xmE3ylEllWxephHFiVwhit0ShZh5OvPyjjJ6HMybuHOxN5lA0KvhIG5TfgmdudKCVTU7HHJFt02QXnkGqog+5dTpb/a77cGZrGaHrnh7aYgiZm41tny7fi0PjX/XB/9/IGUEsDBBQAAAAIAAAAIVBhey9DiQAAAPIAAAALAAAAX3JlbHMvLnJlbHONzzsOAiEQBuCrEA6ws1pYGKCy2dZ4AQLDIy6PDBj19lJYrMbCcuaffH9GnHHVPZbcQqyNPdKam+Sh93oEaCZg0m0qFfNIXKGk+xjJQ9Xmqj3Cfp4PQFuDK7E12WIlp8XuOLs8K/5jF+eiwVMxt4S5/6j4uhiyJo9d8nshC/a9ngbLQQn4eFG9AFBLAwQUAAAACAAAACFQZhg8uIUAAAC1AAAAEQAAAHdvcmQvZG9jdW1lbnQueG1sRY47DsIwDIavUvUAdcXAEIXubFwhJKYtquPIcZVye5IysHyW/T9kW0xgvxNG7Q7aYjbl1i+qyQBkvyC5PHDCWLUXCzmtq8xQWEIS9pjzGmfa4DKOVyC3xn6yxTw5fNpMDdKg050Si2Loau6NXrs9Bac4WGhqo5w8M7kaHgLn4VcG/0enL1BLAQIUABQAAAAIAAAAIVD3S4B1wgAAAHYBAAATAAAAAAAAAAAAAACAAQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAhQAFAAAAAgAAAAhUGF7L0OJAAAA8gAAAAsAAAAAAAAAAAAAAIAB8wAAAF9yZWxzLy5yZWxzUEsBAhQAFAAAAAgAAAAhUGYYPLiFAAAAtQAAABEAAAAAAAAAAAAAAIABpQEAAHdvcmQvZG9jdW1lbnQueG1sUEsFBgAAAAADAAMAuQAAAFkCAAAAAA==";
const insertedRange: Word.Range = paragraphRange.insertFileFromBase64(base64File, Word.InsertLocation.replace);
await context.sync();
console.log("Inserted the embedded document's project update.");
});
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
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 = (document.getElementById("input-footnote") as HTMLInputElement).value;
const footnote: Word.NoteItem = context.document.getSelection().insertFootnote(text);
await context.sync();
console.log("Inserted footnote.");
});
insertGeometricShape(geometricShapeType, insertShapeOptions)
Inserts a geometric shape in front of text with its anchor at the beginning of the range.
insertGeometricShape(geometricShapeType: Word.GeometricShapeType, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;
Parameters
- geometricShapeType
- Word.GeometricShapeType
The geometric type of the shape to insert.
- insertShapeOptions
- Word.InsertShapeOptions
Optional. The location and size of the geometric shape. The default location and size is (0, 0, 100, 100).
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-geometric-shapes.yaml
await Word.run(async (context) => {
// Inserts a moon geometric shape at the beginning of the selection.
const selection: Word.Range = context.document.getSelection();
const shapeOptions: Word.InsertShapeOptions = {
height: 120,
width: 120,
left: 120,
};
selection.insertGeometricShape(Word.GeometricShapeType.moon, shapeOptions);
await context.sync();
console.log("Inserted a moon.");
});
insertGeometricShape(geometricShapeType, insertShapeOptions)
Inserts a geometric shape in front of text with its anchor at the beginning of the range.
insertGeometricShape(geometricShapeType: "LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus", insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;
Parameters
- geometricShapeType
-
"LineInverse" | "Triangle" | "RightTriangle" | "Rectangle" | "Diamond" | "Parallelogram" | "Trapezoid" | "NonIsoscelesTrapezoid" | "Pentagon" | "Hexagon" | "Heptagon" | "Octagon" | "Decagon" | "Dodecagon" | "Star4" | "Star5" | "Star6" | "Star7" | "Star8" | "Star10" | "Star12" | "Star16" | "Star24" | "Star32" | "RoundRectangle" | "Round1Rectangle" | "Round2SameRectangle" | "Round2DiagonalRectangle" | "SnipRoundRectangle" | "Snip1Rectangle" | "Snip2SameRectangle" | "Snip2DiagonalRectangle" | "Plaque" | "Ellipse" | "Teardrop" | "HomePlate" | "Chevron" | "PieWedge" | "Pie" | "BlockArc" | "Donut" | "NoSmoking" | "RightArrow" | "LeftArrow" | "UpArrow" | "DownArrow" | "StripedRightArrow" | "NotchedRightArrow" | "BentUpArrow" | "LeftRightArrow" | "UpDownArrow" | "LeftUpArrow" | "LeftRightUpArrow" | "QuadArrow" | "LeftArrowCallout" | "RightArrowCallout" | "UpArrowCallout" | "DownArrowCallout" | "LeftRightArrowCallout" | "UpDownArrowCallout" | "QuadArrowCallout" | "BentArrow" | "UturnArrow" | "CircularArrow" | "LeftCircularArrow" | "LeftRightCircularArrow" | "CurvedRightArrow" | "CurvedLeftArrow" | "CurvedUpArrow" | "CurvedDownArrow" | "SwooshArrow" | "Cube" | "Can" | "LightningBolt" | "Heart" | "Sun" | "Moon" | "SmileyFace" | "IrregularSeal1" | "IrregularSeal2" | "FoldedCorner" | "Bevel" | "Frame" | "HalfFrame" | "Corner" | "DiagonalStripe" | "Chord" | "Arc" | "LeftBracket" | "RightBracket" | "LeftBrace" | "RightBrace" | "BracketPair" | "BracePair" | "Callout1" | "Callout2" | "Callout3" | "AccentCallout1" | "AccentCallout2" | "AccentCallout3" | "BorderCallout1" | "BorderCallout2" | "BorderCallout3" | "AccentBorderCallout1" | "AccentBorderCallout2" | "AccentBorderCallout3" | "WedgeRectCallout" | "WedgeRRectCallout" | "WedgeEllipseCallout" | "CloudCallout" | "Cloud" | "Ribbon" | "Ribbon2" | "EllipseRibbon" | "EllipseRibbon2" | "LeftRightRibbon" | "VerticalScroll" | "HorizontalScroll" | "Wave" | "DoubleWave" | "Plus" | "FlowChartProcess" | "FlowChartDecision" | "FlowChartInputOutput" | "FlowChartPredefinedProcess" | "FlowChartInternalStorage" | "FlowChartDocument" | "FlowChartMultidocument" | "FlowChartTerminator" | "FlowChartPreparation" | "FlowChartManualInput" | "FlowChartManualOperation" | "FlowChartConnector" | "FlowChartPunchedCard" | "FlowChartPunchedTape" | "FlowChartSummingJunction" | "FlowChartOr" | "FlowChartCollate" | "FlowChartSort" | "FlowChartExtract" | "FlowChartMerge" | "FlowChartOfflineStorage" | "FlowChartOnlineStorage" | "FlowChartMagneticTape" | "FlowChartMagneticDisk" | "FlowChartMagneticDrum" | "FlowChartDisplay" | "FlowChartDelay" | "FlowChartAlternateProcess" | "FlowChartOffpageConnector" | "ActionButtonBlank" | "ActionButtonHome" | "ActionButtonHelp" | "ActionButtonInformation" | "ActionButtonForwardNext" | "ActionButtonBackPrevious" | "ActionButtonEnd" | "ActionButtonBeginning" | "ActionButtonReturn" | "ActionButtonDocument" | "ActionButtonSound" | "ActionButtonMovie" | "Gear6" | "Gear9" | "Funnel" | "MathPlus" | "MathMinus" | "MathMultiply" | "MathDivide" | "MathEqual" | "MathNotEqual" | "CornerTabs" | "SquareTabs" | "PlaqueTabs" | "ChartX" | "ChartStar" | "ChartPlus"
The geometric type of the shape to insert.
- insertShapeOptions
- Word.InsertShapeOptions
Optional. The location and size of the geometric shape. The default location and size is (0, 0, 100, 100).
Returns
Remarks
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
The HTML to be inserted.
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
The value must be replace, start, end, before, or after.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml
// Replaces the first paragraph's content with formatted HTML.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const insertedRange: Word.Range = paragraphRange.insertHtml("<b>Project update:</b> <i>ready for review.</i>", Word.InsertLocation.replace);
await context.sync();
console.log("Inserted bold and italic text from HTML.");
});
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
The Base64-encoded image to be inserted.
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
The value must be replace, start, end, before, or after.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-shapes-text-boxes.yaml
await Word.run(async (context) => {
// Inserts a picture at the start of the first text box.
const firstShapeWithTextBox: Word.Shape = context.document.body.shapes
.getByTypes([Word.ShapeType.textBox])
.getFirst();
firstShapeWithTextBox.load("type/body");
await context.sync();
const startRange: Word.Range = firstShapeWithTextBox.body.getRange(Word.RangeLocation.start);
const newPic: Word.InlinePicture = startRange.insertInlinePictureFromBase64(
getPictureBase64(),
Word.InsertLocation.start
);
newPic.load();
await context.sync();
console.log("New inline picture properties:", newPic);
});
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
The OOXML to be inserted.
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
The value must be replace, start, end, before, or after.
Returns
Remarks
Insertion isn't supported if the content being inserted contains linked or external content. If it does, this method returns an InvalidArgument error.
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/insert-and-read-formatted-content.yaml
// Replaces the first paragraph with a bold paragraph from an OOXML package.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const ooxml: string =
`<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: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:r><w:rPr><w:b/></w:rPr><w:t>Project update from OOXML.</w:t></w:r></w:p></w:body>
</w:document></pkg:xmlData>
</pkg:part>
</pkg:package>`;
const insertedRange: Word.Range = paragraphRange.insertOoxml(ooxml, Word.InsertLocation.replace);
await context.sync();
console.log("Inserted a bold paragraph from OOXML.");
});
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
The paragraph text to be inserted.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Adds a paragraph after the first paragraph range.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const newParagraph: Word.Paragraph = paragraphRange.insertParagraph("Additional project details.", Word.InsertLocation.after);
await context.sync();
console.log("Inserted a paragraph after the summary.");
});
insertPictureFromBase64(base64EncodedImage, insertShapeOptions)
Inserts a floating picture in front of text with its anchor at the beginning of the range.
insertPictureFromBase64(base64EncodedImage: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;
Parameters
- base64EncodedImage
-
string
The Base64-encoded image to be inserted.
- insertShapeOptions
- Word.InsertShapeOptions
Optional. The location and size of the picture. The default location is (0, 0) and the default size is the image's original size.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/15-images/insert-and-inspect-floating-pictures-desktop.yaml
// Anchors a floating picture at the start of the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const pictureOptions: Word.InsertShapeOptions = { left: 20, top: 20, width: 90, height: 39 };
const picture: Word.Shape = paragraphRange.insertPictureFromBase64(
"iVBORw0KGgoAAAANSUhEUgAAAB4AAAANCAIAAAAxEEnAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACFSURBVDhPtY1BEoQwDMP6/0+XgIMTBAeYoTqso9Rkx1zG+tNj1H94jgGzeNSjteO5vtQQuG2seO0av8LzGbe3anzRoJ4ybm/VeKEerAEbAUpW4aWQCmrGFWykRzGBCnYy2ha3oAIq2MloW9yCCqhgJ6NtcQsqoIKdjLbFLaiACnYyf2fODbrjZcXfr2F4AAAAAElFTkSuQmCC",
pictureOptions
);
picture.name = "FloatingPictureSample";
await context.sync();
console.log("Inserted a floating picture anchored to the first paragraph. Get anchored shapes to inspect it.");
});
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
The number of rows in the table.
- columnCount
-
number
The number of columns in the table.
- values
-
string[][]
Optional 2D array. Cells are filled if the corresponding strings are specified in the array.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/inspect-range-structure.yaml
// Adds a project status table after the last paragraph range.
await Word.run(async (context) => {
const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
const projectTable: Word.Table = lastRange.insertTable(2, 2, Word.InsertLocation.after, [
["Task", "Status"],
["Review", "Ready"]
]);
await context.sync();
console.log("Inserted a project status table.");
});
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
Text to be inserted.
- insertLocation
-
Word.InsertLocation | "Replace" | "Start" | "End" | "Before" | "After"
The value must be replace, start, end, before, or after.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Replaces the first paragraph's text without replacing its paragraph mark.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange(Word.RangeLocation.content);
const insertedRange: Word.Range = paragraphRange.insertText("Updated project summary.", Word.InsertLocation.replace);
await context.sync();
console.log("Replaced the first paragraph's text.");
});
insertTextBox(text, insertShapeOptions)
Inserts a floating text box in front of text with its anchor at the beginning of the range.
insertTextBox(text?: string, insertShapeOptions?: Word.InsertShapeOptions): Word.Shape;
Parameters
- text
-
string
Optional. The text to insert into the text box.
- insertShapeOptions
- Word.InsertShapeOptions
Optional. The location and size of the text box. The default location and size is (0, 0, 100, 100).
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/45-shapes/manage-shapes-text-boxes.yaml
await Word.run(async (context) => {
// Inserts a text box at the beginning of the selection.
const range: Word.Range = context.document.getSelection();
const insertShapeOptions: Word.InsertShapeOptions = {
top: 0,
left: 0,
height: 100,
width: 100
};
const newTextBox: Word.Shape = range.insertTextBox("placeholder text", insertShapeOptions);
await context.sync();
console.log("Inserted a text box at the beginning of the current selection.");
});
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
Another range.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml
// Gets the overlap between the document body and its first paragraph.
await Word.run(async (context) => {
const bodyRange: Word.Range = context.document.body.getRange();
const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const overlap: Word.Range = bodyRange.intersectWith(firstRange);
overlap.load("text");
await context.sync();
console.log(`Overlapping text: ${overlap.text}`);
});
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
Another range.
Returns
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/compare-location.yaml
// Checks whether the selection overlaps the first paragraph.
await Word.run(async (context) => {
const firstRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const selection: Word.Range = context.document.getSelection();
const overlap: Word.Range = firstRange.intersectWithOrNullObject(selection);
overlap.load("text");
await context.sync();
if (overlap.isNullObject) {
console.warn("The selection does not overlap or adjoin the first paragraph.");
return;
}
console.log(`Overlapping text: ${overlap.text}`);
});
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()
Removes the highlight added by the highlight method if any.
removeHighlight(): void;
Returns
void
Remarks
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml
// Removes the temporary highlight from the final paragraph.
await Word.run(async (context) => {
const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
lastRange.removeHighlight();
await context.sync();
console.log("Removed the temporary highlight.");
});
search(searchText, searchOptions)
Performs a search with the specified search options 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
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/basic-range-operations.yaml
// Finds whole-word matches within the first paragraph.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const searchOptions: Word.SearchOptions = Word.SearchOptions.newObject(context);
searchOptions.matchCase = false;
searchOptions.matchWholeWord = true;
const matches: Word.RangeCollection = paragraphRange.search("project", searchOptions);
matches.load("items/text");
await context.sync();
console.log(`Matches found: ${matches.items.length}`);
matches.items.forEach((match: Word.Range) => console.log(match.text));
});
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/scroll-to-range.yaml
// Selects the final paragraph and scrolls it into view.
await Word.run(async (context) => {
const lastRange: Word.Range = context.document.body.paragraphs.getLast().getRange();
lastRange.select();
await context.sync();
});
select(selectionMode)
Selects and navigates the Word UI to the range.
select(selectionMode?: "Select" | "Start" | "End"): void;
Parameters
- selectionMode
-
"Select" | "Start" | "End"
Optional. The selection mode must be select, start, or end. select is the default.
Returns
void
Remarks
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[]
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
Examples
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/35-ranges/split-words-of-first-paragraph.yaml
// Splits the first paragraph into words and highlights them in sequence.
await Word.run(async (context) => {
const paragraphRange: Word.Range = context.document.body.paragraphs.getFirst().getRange();
const words: Word.RangeCollection = paragraphRange.split([" "], false, true, true);
words.load("text");
await context.sync();
for (let i = 0; i < words.items.length; i++) {
if (i >= 1) {
words.items[i - 1].font.highlightColor = "#FFFFFF";
}
words.items[i].font.highlightColor = "#FFFF00";
await context.sync();
await new Promise((resolve) => setTimeout(resolve, 200));
}
});
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's 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
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
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
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>;