Haris Jamil
Haris Jamil

Reputation: 133

Removing text of NamedRange leaves an empty paragraph on the line

I want to delete all the name ranges from google doc, but when i delete them using the following code the text and namedRanges are deleted by it leaves an empty paragraph at the place of each namedRange.

nameRanges.forEach(function (rangeEntry) {
    var ele = rangeEntry.getRange().getRangeElements()[0];
    var sOffset = ele.getStartOffset();
    var eOffset = ele.getEndOffsetInclusive();
    var txtObj = ele.getElement().asText();
    txtObj.deleteText(sOffset, eOffset);
    rangeEntry.remove();
}

i am accessing the paragraphs using below code, and their text property is returning as empty string.

body.getParagraphs().forEach( function (para, ind) {             
    console.log('para', para.editAsText().getText());             
})

How can i delete nameRange so it doesn't leave anything behind? Thanks

Upvotes: 0

Views: 95

Answers (1)

Tanaike
Tanaike

Reputation: 201513

  • You want to delete all named ranges.
  • You want to also delete the paragraphs which has the named ranges, while the named ranges are deleted.

If my understanding is correct, how about this modification? In this modification, I used removeFromParent(). Please think of this as just one of several answers.

Modification point:

  • Retrieve the parent of the element from var ele = rangeEntry.getRange().getRangeElements()[0]. Then, the parent is removed by removeFromParent().

Modified script:

nameRanges.forEach(function (rangeEntry) {
  var ele = rangeEntry.getRange().getRangeElements()[0];

  var parent = ele.getElement().getParent(); // Added
  parent.removeFromParent(); // Added

  rangeEntry.remove();
});
  • By the way, when clear() is used instead of removeFromParent(), I think that the result is the same with your current script.

References:

If I misunderstood your question and this was not the result you want, I apologize. At that time, can you provide the sample Document you want to use? By this, I would like to confirm your situation. Of course, please remove your personal information from the sample Document.

Upvotes: 2

Related Questions