javascriptoffice365office-jsadd-inword-addins

how can I get `parentSectionOrNullObject` Range in word? using Office javascript Api?


I am using this but this is giveing error TypeError: Cannot read properties of undefined (reading 'isNullObject') when I am using breakpoint then this is give selection.parentSectionOrNullObject undefined.no idea why irs gives error.

parentSectionOrNullObject = undefined image error image

 async function getSectionRange() {
     try {
         await Word.run(async (context) => {
             const selection = context.document.getSelection();
             selection.load('parentSectionOrNullObject');

             await context.sync();

             if (!selection.parentSectionOrNullObject.isNullObject) {
                 const parentSection = selection.parentSectionOrNullObject;
                 const sectionRange = parentSection.getRange("Whole");

                 context.load(sectionRange, 'text');

                 await context.sync();

                 console.log('Section Range Text:', sectionRange.text);
             } else {
                 console.log('The selection is not within a section.');
             }
         });
     } catch (error) {
         console.error('Error: ', error);
     }
 }


Solution

  • Your selection variable is a Range object. Range does not have a parentSectionOrNullObject property. That property is only found on the Body object. As I explained in my answer to your other question: how can I get Word.Section Range using office javascript api?, you need to get the parent body of selection first.