Headings
The comark/plugins/headings plugin extracts the page title and description from the top of a document and stores them in tree.meta.title and tree.meta.description. By default it reads the first h1 as the title and the first p as the description, then removes both nodes from the tree so they are not rendered twice.
Usage
import { parse } from 'comark'
import headings from 'comark/plugins/headings'
const result = await parse(content, {
plugins: [headings()]
})
console.log(result.meta.title) // "My Page Title"
console.log(result.meta.description) // "First paragraph text."API
headings(options?)
Returns a ComarkPlugin that extracts title and description metadata from top-level nodes.
Parameters:
options?- Optional configuration — see Options
Returns: ComarkPlugin
Results are stored at tree.meta.title and tree.meta.description. Neither field is set when the corresponding node is absent or does not match the configured tag.
Options
| Option | Type | Default | Description |
|---|---|---|---|
titleTag | string | 'h1' | Element tag to extract as the page title |
descriptionTag | string | 'p' | Element tag to extract as the page description |
remove | boolean | true | Remove extracted nodes from the tree after extraction |
titleTag
The element tag to read the title from.
headings({ titleTag: 'h2' })Default: 'h1'
descriptionTag
The element tag to read the description from. Use 'blockquote' if you prefer a block quote as the lead-in description.
headings({ descriptionTag: 'blockquote' })Default: 'p'
remove
Whether to remove the extracted nodes from the tree after extraction. Set to false when you want the metadata available but still need the nodes rendered — for example, when a custom component handles the h1 display.
headings({ remove: false })Default: true
Examples
Default Extraction
# My Page Title
This is the opening paragraph used as the description.
## Section One
More content here.import { parse } from 'comark'
import headings from 'comark/plugins/headings'
const result = await parse(content, {
plugins: [headings()]
})
console.log(result.meta.title) // "My Page Title"
console.log(result.meta.description) // "This is the opening paragraph used as the description."
// result.nodes no longer contains the h1 or the first pBlockquote as Description
const result = await parse(content, {
plugins: [headings({ descriptionTag: 'blockquote' })]
})
console.log(result.meta.description) // "A highlighted lead-in sentence shown as the description."Combining with the TOC Plugin
import { parse } from 'comark'
import headings from 'comark/plugins/headings'
import toc from 'comark/plugins/toc'
const result = await parse(content, {
plugins: [headings(), toc()]
})
console.log(result.meta.title) // page title
console.log(result.meta.description) // page description
console.log(result.meta.toc) // table of contents