setAttributes in Google Doc header failing - setAttibutes is not a function

Viewed 125

I want to set the font size in a google doc header, but I get the error 'setAttributes is not a function'. I can't really understand the structure of a header (it seems), as to where to set the attributes.

      var style = {};
      style[DocumentApp.Attribute.FONT_SIZE] = 16;
      style[DocumentApp.Attribute.BOLD] = true;
      var range = this.Doc.getHeader(
      range.setText(text)
      var m = range.getNumChildren();
      for (var i =0; i<m;i++){
        var cld = range.getChild(i);
        var ct = cld.getText();
        var cat = cld.getAttributes();
        cld.setAttibutes(style);
      }

In the code above I can set the text in the header, and I can see the text in the 1st child element "ct", but I can't set the attributes. cld.getAttributes() returns nulls, so I'm thinking the attributes are set on a higher element. I just don't know which.

1 Answers

Issue:

  • getChild returns element, not Text, thus you need to change cld to Text via asText and then use getText().
  • As for the setAttributes function, I didn't encounter the issue you had, it just worked so I have no clue on why it errors on yours.

Can you try this one?

Code:

function updateHeader() {
  var doc = DocumentApp.getActiveDocument(); 
  var range = doc.getHeader();

  var text = "this is the new header";
  var style = {};
  style[DocumentApp.Attribute.FONT_SIZE] = 16;
  style[DocumentApp.Attribute.BOLD] = true;

  var m = range.getNumChildren();
  for (var i = 0; i < m; i++){
    var cld = range.getChild(i);
    var ct = cld.asText().getText();    // get text value
    var cat = cld.getAttributes();      // get attributes
    Logger.log(ct);                     // print old text
    Logger.log(cat);                    // print old attributes
    
    cld.asText().setText(text);         // set text as header value
    cld.setAttributes(style);           // set attributes
    Logger.log(cld.asText().getText()); // print new text
    Logger.log(cld.getAttributes());    // print new attributes
  }
}

Sample:

sample

Output:

output

Logs:

logs

Note:

  • I placed setText inside the loop to show you the difference of before and after the update of the value of the text and attribute.
Related