Word.ContentControl class

Represents a content control. Content controls are bounded and potentially labeled regions in a document that serve as containers for specific types of content. Individual content controls may contain contents such as images, tables, or paragraphs of formatted text. Currently, only rich text, plain text, and checkbox content controls are supported.

Extends

Remarks

[ API set: WordApi 1.1 ]

Examples

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

    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;

    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'color,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');

        // Synchronize the document state by executing the queued commands,
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' +
            '   ----- appearance: ' + contentControls.items[0].appearance +
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});

Properties

appearance

Specifies the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'.

cannotDelete

Specifies a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited.

cannotEdit

Specifies a value that indicates whether the user can edit the contents of the content control.

color

Specifies the color of the content control. Color is specified in '#RRGGBB' format or by using the color name.

contentControls

Gets the collection of content control objects in the content control.

context

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

font

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

id

Gets an integer that represents the content control identifier.

inlinePictures

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

paragraphs

Gets the collection of paragraph objects in the content control.

parentContentControl

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

placeholderText

Specifies the placeholder text of the content control. Dimmed text will be displayed when the content control is empty.

removeWhenEdited

Specifies a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete.

style

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

tag

Specifies a tag to identify a content control.

text

Gets the text of the content control.

title

Specifies the title for a content control.

type

Gets the content control type. Only rich text, plain text, and checkbox content controls are supported currently.

Methods

clear()

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

delete(keepContent)

Deletes the content control and its content. If keepContent is set to true, the content isn't deleted.

getHtml()

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

getOoxml()

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

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls.

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the content control at the specified location.

insertHtml(html, insertLocation)

Inserts HTML into the content control at the specified location.

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts an inline picture into the content control at the specified location.

insertOoxml(ooxml, insertLocation)

Inserts OOXML into the content control at the specified location.

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

insertText(text, insertLocation)

Inserts text into the content control at the specified location.

load(options)

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

load(propertyNames)

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

load(propertyNamesAndPaths)

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

search(searchText, searchOptions)

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

select(selectionMode)

Selects the content control. This causes Word to scroll to the selection.

select(selectionModeString)

Selects the content control. This causes Word to scroll to the selection.

set(properties, options)

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

set(properties)

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

toJSON()

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

track()

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

untrack()

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

Property Details

appearance

Specifies the appearance of the content control. The value can be 'BoundingBox', 'Tags', or 'Hidden'.

appearance: Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden";

Property Value

Word.ContentControlAppearance | "BoundingBox" | "Tags" | "Hidden"

Remarks

[ API set: WordApi 1.1 ]

cannotDelete

Specifies a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited.

cannotDelete: boolean;

Property Value

boolean

Remarks

[ API set: WordApi 1.1 ]

cannotEdit

Specifies a value that indicates whether the user can edit the contents of the content control.

cannotEdit: boolean;

Property Value

boolean

Remarks

[ API set: WordApi 1.1 ]

color

Specifies the color of the content control. Color is specified in '#RRGGBB' format or by using the color name.

color: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

contentControls

Gets the collection of content control objects in the content control.

readonly contentControls: Word.ContentControlCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

context

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

context: RequestContext;

Property Value

font

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

readonly font: Word.Font;

Property Value

Remarks

[ API set: WordApi 1.1 ]

id

Gets an integer that represents the content control identifier.

readonly id: number;

Property Value

number

Remarks

[ API set: WordApi 1.1 ]

inlinePictures

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

readonly inlinePictures: Word.InlinePictureCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

paragraphs

Gets the collection of paragraph objects in the content control.

readonly paragraphs: Word.ParagraphCollection;

Property Value

Remarks

[ API set: WordApi 1.1 ]

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

parentContentControl

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

readonly parentContentControl: Word.ContentControl;

Property Value

Remarks

[ API set: WordApi 1.1 ]

placeholderText

Specifies the placeholder text of the content control. Dimmed text will be displayed when the content control is empty.

placeholderText: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

removeWhenEdited

Specifies a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete.

removeWhenEdited: boolean;

Property Value

boolean

Remarks

[ API set: WordApi 1.1 ]

style

Specifies the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property.

style: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

tag

Specifies a tag to identify a content control.

tag: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Traverses each paragraph of the document and wraps a content control on each with either a even or odd tags.
await Word.run(async (context) => {
  let paragraphs = context.document.body.paragraphs;
  paragraphs.load("$none"); // Don't need any properties; just wrap each paragraph with a content control.

  await context.sync();

  for (let i = 0; i < paragraphs.items.length; i++) {
    let contentControl = paragraphs.items[i].insertContentControl();
    // For even, tag "even".
    if (i % 2 === 0) {
      contentControl.tag = "even";
    } else {
      contentControl.tag = "odd";
    }
  }
  console.log("Content controls inserted: " + paragraphs.items.length);

  await context.sync();
});

text

Gets the text of the content control.

readonly text: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

title

Specifies the title for a content control.

title: string;

Property Value

string

Remarks

[ API set: WordApi 1.1 ]

type

Gets the content control type. Only rich text, plain text, and checkbox content controls are supported currently.

readonly type: Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText";

Property Value

Word.ContentControlType | "Unknown" | "RichTextInline" | "RichTextParagraphs" | "RichTextTableCell" | "RichTextTableRow" | "RichTextTable" | "PlainTextInline" | "PlainTextParagraph" | "Picture" | "BuildingBlockGallery" | "CheckBox" | "ComboBox" | "DropDownList" | "DatePicker" | "RepeatingSection" | "RichText" | "PlainText"

Remarks

[ API set: WordApi 1.1 ]

Method Details

clear()

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

clear(): void;

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the content controls collection.
    contentControls.load('text');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (contentControls.items.length === 0) {
        console.log("There isn't a content control in this document.");
    } else {
        // Queue a command to clear the contents of the first content control.
        contentControls.items[0].clear();

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

delete(keepContent)

Deletes the content control and its content. If keepContent is set to true, the content isn't deleted.

delete(keepContent: boolean): void;

Parameters

keepContent

boolean

Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content isn't deleted.

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the content controls collection.
    contentControls.load('text');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
        
    if (contentControls.items.length === 0) {
        console.log("There isn't a content control in this document.");
    } else {            
        // Queue a command to delete the first content control. 
        // The contents will remain in the document.
        contentControls.items[0].delete(true);

        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control cleared of contents.'); 
    }
});
// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/content-control-ondeleted-event.yaml

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls.getByTag("forTesting");
  contentControls.load("items");
  await context.sync();

  if (contentControls.items.length === 0) {
    console.log("There are no content controls in this document.");
  } else {
    console.log("Control to be deleted:", contentControls.items[0]);
    contentControls.items[0].delete(false);
    await context.sync();
  }
});

getHtml()

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

getHtml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection that contains a specific tag.
    const contentControlsWithTag = context.document.contentControls.getByTag('Customer-Address');
    
    // Queue a command to load the tag property for all of content controls.
    contentControlsWithTag.load('tag');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControlsWithTag.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the HTML contents of the first content control.
        const html = contentControlsWithTag.items[0].getHtml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control HTML: ' + html.value);
    }
});

getOoxml()

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

getOoxml(): OfficeExtension.ClientResult<string>;

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to get the OOXML contents of the first content control.
        const ooxml = contentControls.items[0].getOoxml();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Content control OOXML: ' + ooxml.value);
    }
});

insertBreak(breakType, insertLocation)

Inserts a break at the specified location in the main document. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls.

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

Parameters

breakType

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

Required. Type of break.

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

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

Returns

void

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of content controls.
    contentControls.load('id');
    
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    // We now will have access to the content control collection.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a page break after the first content control.
        contentControls.items[0].insertBreak(Word.BreakType.page, Word.InsertLocation.after);
        
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a page break after the first content control.');    
    }
});

insertFileFromBase64(base64File, insertLocation)

Inserts a document into the content control at the specified location.

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

Parameters

base64File

string

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

insertLocation

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

Required. The value must be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls.

Returns

Remarks

[ API set: WordApi 1.1 ]

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

insertHtml(html, insertLocation)

Inserts HTML into the content control at the specified location.

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

Parameters

html

string

Required. The HTML to be inserted in to the content control.

insertLocation

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

Required. The value must be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put HTML into the contents of the first content control.
        contentControls.items[0].insertHtml(
            '<strong>HTML content inserted into the content control.</strong>',
            'Start');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted HTML in the first content control.');
    }
});

insertInlinePictureFromBase64(base64EncodedImage, insertLocation)

Inserts an inline picture into the content control at the specified location.

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

Parameters

base64EncodedImage

string

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

insertLocation

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

Required. The value must be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls.

Returns

Remarks

[ API set: WordApi 1.2 ]

insertOoxml(ooxml, insertLocation)

Inserts OOXML into the content control at the specified location.

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

Parameters

ooxml

string

Required. The OOXML to be inserted in to the content control.

insertLocation

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

Required. The value must be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to put OOXML into the contents of the first content control.
        contentControls.items[0].insertOoxml("<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'><pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'><pkg:xmlData><Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'><Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/></Relationships></pkg:xmlData></pkg:part><pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'><pkg:xmlData><w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' ><w:body><w:p><w:pPr><w:spacing w:before='360' w:after='0' w:line='480' w:lineRule='auto'/><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr></w:pPr><w:r><w:rPr><w:color w:val='70AD47' w:themeColor='accent6'/><w:sz w:val='28'/></w:rPr><w:t>This text has formatting directly applied to achieve its font size, color, line spacing, and paragraph spacing.</w:t></w:r></w:p></w:body></w:document></pkg:xmlData></pkg:part></pkg:package>", "End");
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted OOXML in the first content control.');
    }
});  

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

insertParagraph(paragraphText, insertLocation)

Inserts a paragraph at the specified location.

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

Parameters

paragraphText

string

Required. The paragraph text to be inserted.

insertLocation

start | end | before | after | "Start" | "End" | "Before" | "After"

Required. The value must be 'Start', 'End', 'Before', or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to insert a paragraph after the first content control.
        contentControls.items[0].insertParagraph('Text of the inserted paragraph.', 'After');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Inserted a paragraph after the first content control.');
    }
});  

insertText(text, insertLocation)

Inserts text into the content control at the specified location.

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

Parameters

text

string

Required. The text to be inserted in to the content control.

insertLocation

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

Required. The value must be 'Replace', 'Start', or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to replace text in the first content control.
        contentControls.items[0].insertText('Replaced text in the first content control.', 'Replace');
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Replaced text in the first content control.');
    }
});  

// The Silly stories add-in sample shows how to use the insertText method.
// https://aka.ms/sillystorywordaddin

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.ContentControlLoadOptions): Word.ContentControl;

Parameters

options
Word.Interfaces.ContentControlLoadOptions

Provides options for which properties of the object to load.

Returns

Examples

// Load all of the content control properties
// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    } else {
        // Queue a command to load the properties on the first content control.
        contentControls.items[0].load(  'appearance,' +
                                        'cannotDelete,' +
                                        'cannotEdit,' +
                                        'id,' +
                                        'placeHolderText,' +
                                        'removeWhenEdited,' +
                                        'title,' +
                                        'text,' +
                                        'type,' +
                                        'style,' +
                                        'tag,' +
                                        'font/size,' +
                                        'font/name,' +
                                        'font/color');             
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Property values of the first content control:' + 
            '   ----- appearance: ' + contentControls.items[0].appearance + 
            '   ----- cannotDelete: ' + contentControls.items[0].cannotDelete +
            '   ----- cannotEdit: ' + contentControls.items[0].cannotEdit +
            '   ----- color: ' + contentControls.items[0].color +
            '   ----- id: ' + contentControls.items[0].id +
            '   ----- placeHolderText: ' + contentControls.items[0].placeholderText +
            '   ----- removeWhenEdited: ' + contentControls.items[0].removeWhenEdited +
            '   ----- title: ' + contentControls.items[0].title +
            '   ----- text: ' + contentControls.items[0].text +
            '   ----- type: ' + contentControls.items[0].type +
            '   ----- style: ' + contentControls.items[0].style +
            '   ----- tag: ' + contentControls.items[0].tag +
            '   ----- font size: ' + contentControls.items[0].font.size +
            '   ----- font name: ' + contentControls.items[0].font.name +
            '   ----- font color: ' + contentControls.items[0].font.color);
    }
});  

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

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

Parameters

propertyNamesAndPaths

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

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

Returns

search(searchText, searchOptions)

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

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

Parameters

searchText

string

Required. The search text.

searchOptions

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

Optional. Options for the search.

Returns

Remarks

[ API set: WordApi 1.1 ]

Examples

// Run a batch operation against the Word object model.
await Word.run(async (context) => {
    
    // Create a proxy object for the content controls collection.
    const contentControls = context.document.contentControls;
    
    // Queue a command to load the id property for all of the content controls.
    contentControls.load('id');
     
    // Synchronize the document state by executing the queued commands, 
    // and return a promise to indicate task completion.
    await context.sync();
    if (contentControls.items.length === 0) {
        console.log('No content control found.');
    }
    else {
        // Queue a command to select the first content control.
        contentControls.items[0].select();
    
        // Synchronize the document state by executing the queued commands, 
        // and return a promise to indicate task completion.
        await context.sync();
        console.log('Selected the first content control.');
    }
});  

select(selectionMode)

Selects the content control. This causes Word to scroll to the selection.

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

Parameters

selectionMode
Word.SelectionMode

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

Returns

void

Remarks

[ API set: WordApi 1.1 ]

select(selectionModeString)

Selects the content control. This causes Word to scroll to the selection.

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

Parameters

selectionModeString

"Select" | "Start" | "End"

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

Returns

void

Remarks

[ API set: WordApi 1.1 ]

set(properties, options)

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

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

Parameters

properties
Word.Interfaces.ContentControlUpdateData

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

Examples

// Link to full sample: https://raw.githubusercontent.com/OfficeDev/office-js-snippets/prod/samples/word/10-content-controls/insert-and-change-content-controls.yaml

// Adds title and colors to odd and even content controls and changes their appearance.
await Word.run(async (context) => {
  // Get the complete sentence (as range) associated with the insertion point.
  let evenContentControls = context.document.contentControls.getByTag("even");
  let oddContentControls = context.document.contentControls.getByTag("odd");
  evenContentControls.load("length");
  oddContentControls.load("length");

  await context.sync();

  for (let i = 0; i < evenContentControls.items.length; i++) {
    // Change a few properties and append a paragraph.
    evenContentControls.items[i].set({
      color: "red",
      title: "Odd ContentControl #" + (i + 1),
      appearance: Word.ContentControlAppearance.tags
    });
    evenContentControls.items[i].insertParagraph("This is an odd content control", "End");
  }

  for (let j = 0; j < oddContentControls.items.length; j++) {
    // Change a few properties and append a paragraph.
    oddContentControls.items[j].set({
      color: "green",
      title: "Even ContentControl #" + (j + 1),
      appearance: "Tags"
    });
    oddContentControls.items[j].insertHtml("This is an <b>even</b> content control", "End");
  }

  await context.sync();
});

set(properties)

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

set(properties: Word.ContentControl): void;

Parameters

properties
Word.ContentControl

Returns

void

toJSON()

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

toJSON(): Word.Interfaces.ContentControlData;

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

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

Returns