It is possible target specific elements in a DOM via CSS using selectors

h2 {
  /* property: value; */
}

It is also possible to use CSS selector in JS DOM

const elements = document.querySelector("h2")

With the advent of a JAMstack it is also possible to target Markdown elements using CSS selectors

  • Init the project
npm init -y
{
  ...
  "type": "module"
}

Alternatively, enable it via the command line

npx json -I -f package.json -e 'this.type="module"'
  • Install required dependencies
npm i unified remark-parse remark-stringify unist-util-select
  • Create the post.md file
[//]: # "This is a comment"

## Second level heading A

Paragraph

## Second level heading B
  • Create the index.js script
import fs from "fs"
import markdown from "remark-parse"
import stringify from "remark-stringify"
import unified from "unified"
import util from "unist-util-select"
const { selectAll } = util

let mdast
unified()
  .use(markdown)
  .use(() => tree => (mdast = tree))
  .use(stringify)
  .process(fs.readFileSync("post.md"))

const headingsNodes = selectAll("heading[depth=2]", mdast)
const json = JSON.stringify(headingsNodes, null, 2)

console.log(json)
  • Running the script
node index.js

Prints an array containing both level 2 headings as mdast tree nodes

[
  {
    "type": "heading",
    "depth": 2,
    "children": [
      {
        "type": "text",
        "value": "Second level heading A",
        ...
      }
    ],
    ...
  },
  {
    "type": "heading",
    "depth": 2,
    "children": [
      {
        "type": "text",
        "value": "Second level heading B",
        ...
      }
    ],
    ...
  }
]

The magic is happening because of selectAll function from the unist-util-select package

const headingsNodes = selectAll("heading[depth=2]", mdast)

Sources are available in the repository