Je možné cieliť na konkrétne prvky v DOM cez CSS pomocou selektorov
h2 {
/* property: value; */
}
Je tiež možné použiť CSS selektor v JS DOM
const elements = document.querySelector("h2")
S nástupom JAMstack je tiež možné cieliť na Markdown prvky pomocou CSS selektorov
- Inicializujte projekt
npm init -y
- V
package.jsonzmeňte type na ESM, aby ste povolili príkaz import
{
...
"type": "module"
}
Alternatívne to povolte cez príkazový riadok
npx json -I -f package.json -e 'this.type="module"'
- Nainštalujte požadované závislosti
npm i unified remark-parse remark-stringify unist-util-select
- Vytvorte súbor
post.md
[//]: # "This is a comment"
## Second level heading A
Paragraph
## Second level heading B
- Vytvorte skript
index.js
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)
- Spustenie skriptu
node index.js
Vypíše pole obsahujúce oba nadpisy úrovne 2 ako uzly stromu mdast
[
{
"type": "heading",
"depth": 2,
"children": [
{
"type": "text",
"value": "Second level heading A",
...
}
],
...
},
{
"type": "heading",
"depth": 2,
"children": [
{
"type": "text",
"value": "Second level heading B",
...
}
],
...
}
]
Kúzlo sa deje vďaka funkcii selectAll z balíčka
unist-util-select
const headingsNodes = selectAll("heading[depth=2]", mdast)
Zdrojové kódy sú dostupné v repozitári