Search code examples
javascriptms-wordoffice-jsadd-inword-contentcontrol

Add a content control after an existing content control in word using javascript?


A little more detail: I am inserting (lots of) content controls into a single document. Ideas? Current code:

for(let i=0;i<term.length;i++){
  Word.run(function (context) {
    let range = context.document.body
    // Queue a command to create the content control.
    let myContentControl = range.insertContentControl()
    myContentControl.tag = id[i].toString();
    myContentControl.title = id[i].toString();
    myContentControl.insertHtml(term[i], 'End');
    context.load(myContentControl, 'id');
    return context.sync().then(function () {
    console.log('Created content control with id: ' + myContentControl.id);
  });
})
.catch(function (error) {
  console.log('Error: ' + JSON.stringify(error));
  if (error instanceof OfficeExtension.Error) {
    console.log('Debug info: ' + JSON.stringify(error.debugInfo));
  });
}

Solution

  • Insert Paragraphs based on the number content controls you want to insert inside the word document and insert the content controls looping over the paragraphs.

    Word.run(function (context) {
            var paragraphs = context.document.body.paragraphs;
            context.load(paragraphs, 'text');
            return context.sync().then(function () {
              const loop = paragraphs.items.length;
              var contentControls;
              console.log('loop value',loop);
              for (var x = 0; x < loop; x++) {
                var paragraph;
                paragraph = paragraphs.items[x];
                contentControls = paragraph.insertContentControl();
                contentControls.tag = 'tag';
                contentControls.title = 'title';
              }
            });
          })