Class DocumentTab | Apps Script | Google for Developers (original) (raw)
Google Workspace services
Calendar
- Overview
- CalendarApp
- Classes
- Calendar
- CalendarEvent
- CalendarEventSeries
- EventGuest
- EventRecurrence
- RecurrenceRule
- Enums
- Color
- EventColor
- EventTransparency
- EventType
- GuestStatus
- Visibility
- Advanced services
- Calendar API
Docs
- Overview
- DocumentApp
- Classes
- Body
- Bookmark
- ContainerElement
- Date
- Document
- DocumentTab
- Equation
- EquationFunction
- EquationFunctionArgumentSeparator
- EquationSymbol
- FooterSection
- Footnote
- FootnoteSection
- HeaderSection
- HorizontalRule
- InlineDrawing
- InlineImage
- ListItem
- NamedRange
- PageBreak
- Paragraph
- Person
- Position
- PositionedImage
- Range
- RangeBuilder
- RangeElement
- RichLink
- Tab
- Table
- TableCell
- TableOfContents
- TableRow
- Text
- UnsupportedElement
- Interfaces
- Element
- Enums
- Attribute
- ElementType
- FontFamily
- GlyphType
- HorizontalAlignment
- ParagraphHeading
- PositionedLayout
- TabType
- TextAlignment
- VerticalAlignment
- Advanced services
- Docs API
Drive
- Overview
- DriveApp
- Classes
- File
- FileIterator
- Folder
- FolderIterator
- User
- Enums
- Access
- Permission
- Advanced services
- Drive API
- Drive Activity API
- Drive Labels API
Forms
- Overview
- FormApp
- Classes
- CheckboxGridItem
- CheckboxGridValidation
- CheckboxGridValidationBuilder
- CheckboxItem
- CheckboxValidation
- CheckboxValidationBuilder
- Choice
- DateItem
- DateTimeItem
- DurationItem
- Form
- FormResponse
- GridItem
- GridValidation
- GridValidationBuilder
- ImageItem
- ItemResponse
- ListItem
- MultipleChoiceItem
- PageBreakItem
- ParagraphTextItem
- ParagraphTextValidation
- ParagraphTextValidationBuilder
- QuizFeedback
- QuizFeedbackBuilder
- RatingItem
- ScaleItem
- SectionHeaderItem
- TextItem
- TextValidation
- TextValidationBuilder
- TimeItem
- VideoItem
- Interfaces
- Item
- Enums
- Alignment
- DestinationType
- FeedbackType
- ItemType
- PageNavigationType
- RatingIconType
Gmail
- Overview
- GmailApp
- Classes
- GmailAttachment
- GmailDraft
- GmailLabel
- GmailMessage
- GmailThread
- Advanced services
- Gmail API
Sheets
- Overview
- SpreadsheetApp
- Classes
- Banding
- BooleanCondition
- CellImage
- CellImageBuilder
- Color
- ColorBuilder
- ConditionalFormatRule
- ConditionalFormatRuleBuilder
- ContainerInfo
- DataSource for Connected Sheets
* BigQueryDataSourceSpec
* BigQueryDataSourceSpecBuilder
* DataExecutionStatus
* LookerDataSourceSpec
* LookerDataSourceSpecBuilder
* DataSource
* DataSourceChart
* DataSourceColumn
* DataSourceFormula
* DataSourceParameter
* DataSourcePivotTable
* DataSourceRefreshSchedule
* DataSourceRefreshScheduleFrequency
* DataSourceSheet
* DataSourceSheetFilter
* DataSourceSpec
* DataSourceSpecBuilder
* DataSourceTable
* DataSourceTableColumn
* DataSourceTableFilter - DataValidation
- DataValidationBuilder
- DateTimeGroupingRule
- DeveloperMetadata
- DeveloperMetadataFinder
- DeveloperMetadataLocation
- Drawing
- EmbeddedAreaChartBuilder
- EmbeddedBarChartBuilder
- EmbeddedChart
- EmbeddedChartBuilder
- EmbeddedColumnChartBuilder
- EmbeddedComboChartBuilder
- EmbeddedHistogramChartBuilder
- EmbeddedLineChartBuilder
- EmbeddedPieChartBuilder
- EmbeddedScatterChartBuilder
- EmbeddedTableChartBuilder
- Filter
- FilterCriteria
- FilterCriteriaBuilder
- GradientCondition
- Group
- NamedRange
- OverGridImage
- PageProtection
- PivotFilter
- PivotGroup
- PivotGroupLimit
- PivotTable
- PivotValue
- Protection
- Range
- RangeList
- RichTextValue
- RichTextValueBuilder
- Selection
- Sheet
- Slicer
- SortSpec
- Spreadsheet
- SpreadsheetTheme
- TextFinder
- TextRotation
- TextStyle
- TextStyleBuilder
- ThemeColor
- Enums
- AutoFillSeries
- BandingTheme
- BooleanCriteria
- BorderStyle
- CopyPasteType
- DataValidationCriteria
- DateTimeGroupingRuleType
- DeveloperMetadataLocationType
- DeveloperMetadataVisibility
- Dimension
- Direction
- FrequencyType
- GroupControlTogglePosition
- InterpolationType
- PivotTableSummarizeFunction
- PivotValueDisplayType
- ProtectionType
- RecalculationInterval
- RelativeDate
- SheetType
- SortOrder
- TextDirection
- TextToColumnsDelimiter
- ThemeColorType
- ValueType
- WrapStrategy
- Advanced services
- Sheets API
Slides
- Overview
- SlidesApp
- Classes
- AffineTransform
- AffineTransformBuilder
- AutoText
- Autofit
- Border
- Color
- ColorScheme
- ConnectionSite
- Fill
- Group
- Image
- Layout
- Line
- LineFill
- Link
- List
- ListStyle
- Master
- NotesMaster
- NotesPage
- Page
- PageBackground
- PageElement
- PageElementRange
- PageRange
- Paragraph
- ParagraphStyle
- PictureFill
- Point
- Presentation
- Selection
- Shape
- SheetsChart
- Slide
- SolidFill
- SpeakerSpotlight
- Table
- TableCell
- TableCellRange
- TableColumn
- TableRow
- TextRange
- TextStyle
- ThemeColor
- Video
- WordArt
- Enums
- AlignmentPosition
- ArrowStyle
- AutoTextType
- AutofitType
- CellMergeState
- ContentAlignment
- DashStyle
- FillType
- LineCategory
- LineFillType
- LineType
- LinkType
- ListPreset
- PageBackgroundType
- PageElementType
- PageType
- ParagraphAlignment
- PlaceholderType
- PredefinedLayout
- SelectionType
- ShapeType
- SheetsChartEmbedType
- SlideLinkingMode
- SlidePosition
- SpacingMode
- TextBaselineOffset
- TextDirection
- ThemeColorType
- VideoSourceType
- Advanced services
- Slides API
More...
- Groups
* Overview
* GroupsApp
* Classes
* Group
* Enums
* Role
* Advanced services
* Cloud Identity Groups API
* Migrate from Groups Service - People
* Advanced services
* People API
* Migrate from Contacts service
* Contacts
* Overview
* ContactsApp
* Classes
* AddressField
* CompanyField
* Contact
* ContactGroup
* CustomField
* DateField
* EmailField
* IMField
* PhoneField
* UrlField
* Enums
* ExtendedField
* Field
* Gender
* Priority
* Sensitivity
- Groups
Other Google services
Google Maps
YouTube
- Advanced services
- YouTube Data API
- YouTube Analytics API
- YouTube Content ID API
More...
- Google Ads & Merchant Center
- Google Data Studio
* Overview
* DataStudioApp
* Classes
* BigQueryConfig
* Checkbox
* CommunityConnector
* Config
* DebugError
* Field
* Fields
* GetAuthTypeResponse
* GetDataResponse
* GetSchemaResponse
* Info
* OptionBuilder
* SelectMultiple
* SelectSingle
* SetCredentialsResponse
* TextArea
* TextInput
* UserError
* Enums
* AggregationType
* AuthType
* BigQueryParameterType
* FieldType
Utility services
API & database connections
- JDBC
* Overview
* Jdbc
* Classes
* JdbcArray
* JdbcBlob
* JdbcCallableStatement
* JdbcClob
* JdbcConnection
* JdbcDatabaseMetaData
* JdbcDate
* JdbcParameterMetaData
* JdbcPreparedStatement
* JdbcRef
* JdbcResultSet
* JdbcResultSetMetaData
* JdbcRowId
* JdbcSQLXML
* JdbcSavepoint
* JdbcStatement
* JdbcStruct
* JdbcTime
* JdbcTimestamp
- JDBC
Data usability & optimization
- Optimization
* Overview
* LinearOptimizationService
* Classes
* LinearOptimizationConstraint
* LinearOptimizationEngine
* LinearOptimizationSolution
* Enums
* Status
* VariableType - XML
* Overview
* XmlService
* Classes
* Attribute
* Cdata
* Comment
* DocType
* Document
* Element
* EntityRef
* Format
* Namespace
* ProcessingInstruction
* Text
* Interfaces
* Content
* Enums
* ContentType
- Optimization
HTML & content
- Charts
* Overview
* Charts
* Classes
* AreaChartBuilder
* BarChartBuilder
* Chart
* ChartOptions
* ColumnChartBuilder
* DataTable
* DataTableBuilder
* DataViewDefinition
* DataViewDefinitionBuilder
* LineChartBuilder
* NumberRangeFilterBuilder
* PieChartBuilder
* ScatterChartBuilder
* StringFilterBuilder
* TableChartBuilder
* TextStyle
* TextStyleBuilder
* Interfaces
* DataTableSource
* Enums
* ChartHiddenDimensionStrategy
* ChartMergeStrategy
* ChartType
* ColumnType
* CurveStyle
* MatchType
* Orientation
* PickerValuesLayout
* PointStyle
* Position - HTML
* Overview
* google.script.history (client-side)
* google.script.host (client-side)
* google.script.run (client-side)
* google.script.url (client-side)
* HtmlService
* Classes
* HtmlOutput
* HtmlOutputMetaTag
* HtmlTemplate
* Enums
* SandboxMode
* XFrameOptionsMode
- Charts
Script execution & information
- Base
* Overview
* Browser
* Logger
* MimeType
* Session
* console
* Classes
* Blob
* Menu
* PromptResponse
* RgbColor
* Ui
* User
* Interfaces
* BlobSource
* Enums
* Button
* ButtonSet
* ColorType
* Month
* Weekday - Script
* Overview
* ScriptApp
* Classes
* AuthorizationInfo
* CalendarTriggerBuilder
* ClockTriggerBuilder
* DocumentTriggerBuilder
* FormTriggerBuilder
* Service
* SpreadsheetTriggerBuilder
* StateTokenBuilder
* Trigger
* TriggerBuilder
* Enums
* AuthMode
* AuthorizationStatus
* EventType
* InstallationSource
* TriggerSource
- Base
Script project resources
Manifest
Google Workspace add-ons
Services
- Card
* Overview
* CardService
* Classes
* Action
* ActionResponse
* ActionResponseBuilder
* ActionStatus
* Attachment
* AuthorizationAction
* AuthorizationException
* BorderStyle
* Button
* ButtonSet
* CalendarEventActionResponse
* CalendarEventActionResponseBuilder
* Card
* CardAction
* CardBuilder
* CardHeader
* CardSection
* CardWithId
* Carousel
* CarouselCard
* ChatActionResponse
* ChatClientDataSource
* ChatResponse
* ChatResponseBuilder
* ChatSpaceDataSource
* Chip
* ChipList
* CollapseControl
* Column
* Columns
* ComposeActionResponse
* ComposeActionResponseBuilder
* DatePicker
* DateTimePicker
* DecoratedText
* Dialog
* DialogAction
* Divider
* DriveItemsSelectedActionResponse
* DriveItemsSelectedActionResponseBuilder
* EditorFileScopeActionResponse
* EditorFileScopeActionResponseBuilder
* FixedFooter
* Grid
* GridItem
* HostAppDataSource
* IconImage
* Image
* ImageButton
* ImageComponent
* ImageCropStyle
* KeyValue
* LinkPreview
* MaterialIcon
* Navigation
* Notification
* OpenLink
* OverflowMenu
* OverflowMenuItem
* PlatformDataSource
* SelectionInput
* Suggestions
* SuggestionsResponse
* SuggestionsResponseBuilder
* Switch
* TextButton
* TextInput
* TextParagraph
* TimePicker
* UniversalActionResponse
* UniversalActionResponseBuilder
* UpdateDraftActionResponse
* UpdateDraftActionResponseBuilder
* UpdateDraftBccRecipientsAction
* UpdateDraftBodyAction
* UpdateDraftCcRecipientsAction
* UpdateDraftSubjectAction
* UpdateDraftToRecipientsAction
* UpdatedWidget
* Validation
* Widget
* Enums
* BorderType
* ChipListLayout
* CommonDataSource
* ComposedEmailType
* ContentType
* DisplayStyle
* GridItemLayout
* HorizontalAlignment
* HorizontalSizeStyle
* Icon
* ImageButtonStyle
* ImageCropType
* ImageStyle
* InputType
* Interaction
* LoadIndicator
* OnClose
* OpenAs
* ResponseType
* SelectionInputType
* Status
* SwitchControlType
* TextButtonStyle
* UpdateDraftBodyType
* VerticalAlignment
* WrapStyle - Conferencing Data
* Overview
* ConferenceDataService
* Classes
* ConferenceData
* ConferenceDataBuilder
* ConferenceError
* ConferenceParameter
* EntryPoint
* Enums
* ConferenceErrorType
* EntryPointFeature
* EntryPointType
- Card
Manifest
Apps Script API
v1
- Overview
- REST Resources
- Types
- ExecuteStreamResponse
- ExecutionError
- ExecutionResponse
- File
- LocalizedMessage
- NullValue
Class DocumentTab
Stay organized with collections Save and categorize content based on your preferences.
DocumentTab
A document tab, containing rich text and elements such as tables and lists.
Retrieve a document tab using Document.getTabs()[tabIndex].asDocumentTab()
.
// Get a specific document tab based on the tab ID. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab();
Detailed documentation
addBookmark(position)
Adds a [Bookmark](/apps-script/reference/document/bookmark)
at the given [Position](/apps-script/reference/document/position)
.
// Opens the Docs file and retrieves the tab by its IDs. If you created your // script from within a Google Docs file, you can use // DocumentApp.getActiveDocument().getActiveTab() instead. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab();
// Gets the tab body and adds a paragraph. const paragraph = documentTab.getBody().appendParagraph('My new paragraph.');
// Creates a position at the first character of the paragraph text. const position = documentTab.newPosition(paragraph.getChild(0), 0);
// Adds a bookmark at the first character of the paragraph text. const bookmark = documentTab.addBookmark(position);
// Logs the bookmark ID to the console. console.log(bookmark.getId());
Parameters
Name | Type | Description |
---|---|---|
position | Position | The position of the new bookmark. |
Return
[Bookmark](/apps-script/reference/document/bookmark)
— The new bookmark.
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
addNamedRange(name, range)
Adds a [NamedRange](/apps-script/reference/document/named-range)
, which is a [Range](/apps-script/reference/document/range)
that has a name and ID to use for later retrieval. Names aren't necessarily unique, even across tabs; several different ranges in the same document can share the same name, much like a class in HTML. By contrast, IDs are unique within the document, like an ID in HTML. After you add a NamedRange
you can't modify it, you can only remove it.
Any script that accesses the tab can access a NamedRange
. To avoid unintended conflicts between scripts, consider prefixing range names with a unique string.
// Creates a named range that includes every table in a tab by its ID. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab(); const rangeBuilder = documentTab.newRange(); const tables = documentTab.getBody().getTables(); for (let i = 0; i < tables.length; i++) { rangeBuilder.addElement(tables[i]); } documentTab.addNamedRange('Tab t.0 tables', rangeBuilder.build());
Parameters
Name | Type | Description |
---|---|---|
name | String | The name for the range, which doesn't need to be unique; range names must be between 1-256 characters. |
range | Range | The range of elements to associate with the name; the range can be a search result or manually constructed with newRange(). |
Return
[NamedRange](/apps-script/reference/document/named-range)
— The NamedRange
.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getBody()
Retrieves the tab's [Body](/apps-script/reference/document/body)
.
Tabs may contain different types of sections (for example, [HeaderSection](/apps-script/reference/document/header-section)
, [FooterSection](/apps-script/reference/document/footer-section)
). The active section for a tab is the [Body](/apps-script/reference/document/body)
.
Element methods in DocumentTab
delegate to the [Body](/apps-script/reference/document/body)
.
// Opens the Docs file and retrieves the tab by its IDs. If you created your // script from within a Google Docs file, you can use // DocumentApp.getActiveDocument().getActiveTab() instead. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab();
// Gets the tab body. const body = documentTab.getBody();
// Gets the body text and logs it to the console. console.log(body.getText());
Return
[Body](/apps-script/reference/document/body)
— The tab's body section.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getBookmark(id)
Gets the [Bookmark](/apps-script/reference/document/bookmark)
with the given ID. This method returns null
if no such Bookmark
exists within this tab.
// Opens the Docs file and retrieves the tab by its IDs. If you created your // script from within a Google Docs file, you can use // DocumentApp.getActiveDocument().getActiveTab() instead. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab();
// Gets the bookmark by its ID. const bookmark = documentTab.getBookmark('id.xyz654321');
// If the bookmark exists within the tab, logs the character offset of its // position to the console. Otherwise, logs 'No bookmark exists with the given // ID.' to the console. if (bookmark) { console.log(bookmark.getPosition().getOffset()); } else { console.log('No bookmark exists with the given ID.'); }
Parameters
Name | Type | Description |
---|---|---|
id | String | The ID for the Bookmark. |
Return
[Bookmark](/apps-script/reference/document/bookmark)
— The Bookmark
with the given ID, or null
if no such Bookmark
exists within the tab.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getBookmarks()
Gets all [Bookmark](/apps-script/reference/document/bookmark)
objects in the tab.
// Opens the Docs file and retrieves the tab by its IDs. If you created your // script from within a Google Docs file, you can use // DocumentApp.getActiveDocument().getActiveTab() instead. // TODO(developer): Replace the IDs with your own. const documentTab = DocumentApp.openById('123abc').getTab('123abc').asDocumentTab();
// Gets all of the bookmarks in the tab. const bookmarks = documentTab.getBookmarks();
// Logs the number of bookmarks in the tab to the console. console.log(bookmarks.length);
Return
[Bookmark[]](/apps-script/reference/document/bookmark)
— An array of the Bookmark
objects in the tab.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getNamedRangeById(id)
Gets the [NamedRange](/apps-script/reference/document/named-range)
with the given ID. This method returns null
if no suchNamedRange
exists in the tab. Names are not necessarily unique, even across tabs; several different ranges in the same document may share the same name, much like a class in HTML. By contrast, IDs are unique within the tab, like an ID in HTML.
Parameters
Name | Type | Description |
---|---|---|
id | String | The range's ID, which is unique within the tab. |
Return
[NamedRange](/apps-script/reference/document/named-range)
— The NamedRange
with the given ID, or null
if no such range exists in the tab.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getNamedRanges()
Gets all [NamedRange](/apps-script/reference/document/named-range)
objects in the tab.
A NamedRange
can be accessed by any script that accesses the tab. To avoid unintended conflicts between scripts, consider prefixing range names with a unique string.
Return
[NamedRange[]](/apps-script/reference/document/named-range)
— An array of the NamedRange
objects in the tab, possibly including multiple ranges with the same name.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
getNamedRanges(name)
Gets all [NamedRange](/apps-script/reference/document/named-range)
objects in the tab with the given name. Names are not necessarily unique, even across tabs; several different ranges in the same document may share the same name, much like a class in HTML. By contrast, IDs are unique within the tab, like an ID in HTML.
A NamedRange
can be accessed by any script that accesses the tab. To avoid unintended conflicts between scripts, consider prefixing range names with a unique string.
Parameters
Name | Type | Description |
---|---|---|
name | String | The range's name, which is not necessarily unique. |
Return
[NamedRange[]](/apps-script/reference/document/named-range)
— An array of the NamedRange
objects in the tab with the given name.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
newPosition(element, offset)
Creates a new [Position](/apps-script/reference/document/position)
, which is a reference to a location in the tab, relative to a specific element. The user's cursor is represented as a Position
, among other uses.
// Append a paragraph, then place the user's cursor after the first word of the // new paragraph. // TODO(developer): Replace the IDs with your own. const doc = DocumentApp.openById('123abc'); const documentTab = doc.getTab('123abc').asDocumentTab(); const paragraph = documentTab.getBody().appendParagraph('My new paragraph.'); const position = documentTab.newPosition(paragraph.getChild(0), 2); doc.setCursor(position);
Parameters
Name | Type | Description |
---|---|---|
element | Element | The element that contains the newly created Position to; this must be either a Text element or a container element like Paragraph. |
offset | Integer | For Text elements, the number of characters before the Position; for other elements, the number of child elements before the Position within the same container element. |
Return
[Position](/apps-script/reference/document/position)
— The new Position
.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
newRange()
Creates a builder used to construct [Range](/apps-script/reference/document/range)
objects from tab elements.
// Change the user's selection to a range that includes every table in the tab. // TODO(developer): Replace the IDs with your own. const doc = DocumentApp.openById('123abc'); const documentTab = doc.getTab('123abc').asDocumentTab(); const rangeBuilder = documentTab.newRange(); const tables = documentTab.getBody().getTables(); for (let i = 0; i < tables.length; i++) { rangeBuilder.addElement(tables[i]); } doc.setSelection(rangeBuilder.build());
Return
[RangeBuilder](/apps-script/reference/document/range-builder)
— The new builder.
Authorization
Scripts that use this method require authorization with one or more of the following scopes:
https://www.googleapis.com/auth/documents.currentonly
https://www.googleapis.com/auth/documents
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-12-02 UTC.