Search code examples
javascriptjqueryoffice-jsword-web-addins

Selecting Text in Word Web Add-in using JQuery


I am developing Word web Add-in using OfficeJS, Now I have an accordian, If the user click on accordian menu, I need to make a selection over the header text in Word document, wherever it exists (at least one occurrence).

Is there any way to search the texts and make selection over that in Word doc using OfficeJS.Context ?

Office.context.document.setSelectedDataAsync(WordToSelect, function (asyncResult) {    });

I got the above code, that is inserting the specified text and select instead of searching and do


Solution

  • You need to use the search API on the header for this. Here is a quick sample on how to do it. (assumes "Hello World" is typed on the header :))

    async function run() {
        await Word.run(async (context) => {
    
            let searchResults = context.document.sections.getFirst().getHeader("primary").search("World");
            searchResults.load();
    
            await context.sync();
    
            //select the first one found
            searchResults.items[0].select();
        });
    }
    couple of things to keep in mind when working with headers:

    1. As you probably know, Word documents can have multiple sections and hence multiple sets of headers and footers. So if you want to cover all the cases make sure to traverse the sections collection.
    2. Each section can contain 3 headers/footers, primary, even, first page. would be interesting to see where you will do the search/selection in a situation where you have all options.

    hope this sets you up in the right direction.