Google Docs Script: Trouble with RangeBuilder and Table Elements

Hey everyone, I’m stuck with a Google Docs script. I’m trying to add a table element to a RangeBuilder, but it’s not working. Here’s what’s happening:

I select a table in my doc and run this script:

function doStuff() {
  var myDoc = DocumentApp.getActiveDocument();
  var picked = myDoc.getSelection().getRangeElements();
  var tableStuff = picked[1];
  labelThis(myDoc, tableStuff, 'Cool Table');
}

function labelThis(doc, thing, label) {
  var newRange = doc.newRange();
  newRange.addElement(thing);
  doc.addNamedRange(label, newRange.build());
}

But I get this error:
‘The parameters (DocumentApp.RangeElement) don’t match the method signature for DocumentApp.RangeBuilder.addElement.’

I thought addElement() takes any element. What am I missing? How can I fix this? Thanks for any help!

I’ve run into this issue before, and it can be a bit tricky. The problem is that getRangeElements() returns an array of RangeElement objects, not the actual elements themselves. To fix this, you need to access the actual element within the RangeElement.

Try modifying your code like this:

function doStuff() {
  var myDoc = DocumentApp.getActiveDocument();
  var picked = myDoc.getSelection().getRangeElements();
  var tableStuff = picked[1].getElement();  // Get the actual element
  labelThis(myDoc, tableStuff, 'Cool Table');
}

This should resolve the error you’re seeing. The getElement() method extracts the actual element from the RangeElement object, which is what addElement() expects.

Also, make sure the second element (index 1) in your selection is indeed a table. If it’s not, you might need to adjust the index or add some error checking.

Hope this helps solve your problem!

hey stella, i ran into the same issue. try using .getElement() on your RangeElement to pass the actual element to addElement().

hope this helps!

I encountered a similar issue when working with RangeBuilder and table elements. The key is understanding that getRangeElements() returns RangeElement objects, not the elements themselves. To fix this, you need to use the getElement() method on the RangeElement.

Here’s a modified version of your code that should work:

function doStuff() {
  var myDoc = DocumentApp.getActiveDocument();
  var picked = myDoc.getSelection().getRangeElements();
  var tableStuff = picked[1].getElement();
  labelThis(myDoc, tableStuff, 'Cool Table');
}

This change extracts the actual element from the RangeElement, which is what addElement() expects. Also, ensure that the second element in your selection is indeed a table. If not, you might need to adjust the index or add some error checking logic.

Let me know if this solves your problem or if you need further assistance.