0

I have a document with a Title element at the top and I'm trying to check that the title is centered. I have already setup the following:

  const body = DocumentApp.getActiveDocument().getBody();
  let title = body.getParagraphs()[0];
  let att = title.getAttributes();
}

and when I add Logger.log(att.HORIZONTAL_ALIGNMENT); it returns "Center" but when I try to check against that with Logger.log(att.HORIZONTAL_ALIGNMENT == "Center"); it returns false. Other attribute checks are correct like font size, font face, bold, etc.

Spencer
  • 453
  • 4
  • 21

2 Answers2

0

That property is an ENUM object, so you need to compare it with the relevant attribute of DocumentApp.HorizontalAlignment:

function myFunction() {
  const body = DocumentApp.getActiveDocument().getBody();
  let title = body.getParagraphs()[0];
  let att = title.getAttributes();

  Logger.log(att.HORIZONTAL_ALIGNMENT);
  Logger.log(att.HORIZONTAL_ALIGNMENT === DocumentApp.HorizontalAlignment.CENTER);
}

Note the use of === rather than ==. See here for background on why that is preferred.


Additional Notes:

When you log the value of att.HORIZONTAL_ALIGNMENT to the console, that causes the text representation of the ENUM to be printed, as you saw.

But when you place that same att.HORIZONTAL_ALIGNMENT in an evaluation, it's still an ENUM. It has not been converted to text at the time the evaluation takes place - hence the ENUM object does not equal the "Center" text. They are two different things.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
0

Perhaps this will help:

The document has only one paragraph

function lookingatattributes() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const style1 = {};
  style1[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.CENTER;
  let n = body.getNumChildren();
  for(let i = 0; i<n;i++) {
    let c = body.getChild(i).asParagraph();
    c.setAttributes(style1);
    Logger.log('Child: %s %s %s',i,c.getAttributes()['CENTER'],c.getAttributes()[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]);
  }

}

Execution log
2:36:27 PM  Notice  Execution started
2:36:28 PM  Info    Child: 0.0 null Center
2:36:27 PM  Notice  Execution completed

This is no property "CENTER"

Cooper
  • 59,616
  • 6
  • 23
  • 54