I have created a task pane for word 2016 which has two buttons such as 'addcontentcontrol' and 'retrievecontentcontrol' . Adding a content control in document works fine.When i select that content control's text and hit 'retrievecontentcontrol',it returns text. However, I want to check whether the selected text contains content control or plain text. Thanks a lot in advance.
How to check if selected text contains content control or not in word 2016 using word Javascript api
2 Answers
I think you are asking about two things. If you are selecting a content control's text, and want to return the content control, then you'll want to do the following:
You'll want to check the range.parentContentControl property to check whether the selected text is within a content control. If the returned value is not null, then you may want to compare the text value of the content control and the text value of the selected range to make sure they are equivalent.
var contentControl = context.document.getSelection().parentContentControl;
But if you want to check whether some arbitrary text from a selection contains a content control, then you'll want to check the content control collection on the range.
var contentControlCollection = context.document.getSelection().contentControlCollection;

- 3,387
- 1
- 13
- 32
-
@mike, Thanks for reply, But it's not working.I select entire text inside a contentcontrol which has tag and title values but context.document.getSelection().parentContentControl returns 'undefined'. There are bunch of content controls out there in document, I want to find out which one's text is selected or not. – office365developer Apr 18 '16 at 20:44
-
1I think the second line must use the `contentControls` property and not `contentControlsCollection`, which is a type. Try that @office365developer – Miro J. Sep 19 '16 at 17:08
Maybe that happens because you are not loading the content control before calling context.sync()? ... try this code it must work (note that we get a GeneralException if there is no content control in the selection). Note that This sample assumes that if there is a content control it has a title on it :)
function insideOfContentControlCheck() {
Word.run(function (ctx) {
var myCC = ctx.document.getSelection().parentContentControl;
ctx.load(myCC); // I think this is the part you are missing!
return ctx.sync()
.then(function () {
console.log(myCC.title);// if there is a content control we'll show the title
});
}).catch(function (e) {
//there is no ContentControl.
console.log("Error", e.message);
});
}

- 4,898
- 1
- 8
- 17