Skip to content

Examples (section header)

Bhsd edited this page Apr 15, 2026 · 6 revisions

Renaming a section

Expand

You can rename a section from Reference to References in the content of a page. This example demonstrates the use of HeadingToken.

// Renaming a section (main)
// The content of a page containing a section named `Reference`
var content = `Foo

== Reference ==
Bar`,
	root = Parser.parse(content);
for (const heading of root.querySelectorAll('heading')) {
	if (heading.innerText === 'Reference') {
		heading.innerText = 'References';
	}
}
assert.equal(
	root,
	`Foo

==References==
Bar`,
);

Ordering sections

Expand

You can put the section named Notes before the section named References in the content of a page. This example demonstrates the use of Token.prototype.sections and AstRange.

// Ordering sections (main)
// The content of a page containing sections `Notes` and `References`
var content = `Foo

== References ==
Bar

== Notes ==
Baz`,
	root = Parser.parse(content),
	sections = root.sections(),
	references = sections.find(
		section => section.querySelector('heading[level=2]')?.innerText
			=== 'References',
	),
	notes = sections.find(
		section => section.querySelector('heading[level=2]')?.innerText
			=== 'Notes',
	);
if (references && notes) {
	const {childNodes} = notes;
	// Must remove `notes` before inserting its children before `references`
	notes.remove();
	references.before(...childNodes);
}
assert.equal(
	root,
	`Foo

== Notes ==
Baz
== References ==
Bar

`,
);

Inserting TOC before the first section

Expand

You can insert the magic word __TOC__ before the first section. This example demonstrates the use of AstNode.prototype.before.

// Inserting TOC before the first section (main)
// The content of a page containing a section
var content = `Foo

== Bar ==
Baz`,
	root = Parser.parse(content),
	heading = root.querySelector('heading');
if (heading) {
	heading.before('__TOC__\n');
}
assert.equal(
	root,
	`Foo

__TOC__
== Bar ==
Baz`,
);

Getting the hash of a section

Expand

You can get the hash of a section in the content of a page. This example demonstrates the use of HeadingToken.

// Getting the hash of a section (main)
// The content of a page containing a section
var content = `Foo

== <i>Bar</i> ==
Baz`,
	root = Parser.parse(content),
	heading = root.querySelector('heading'),
	hash = heading && `#${heading.id}`;
assert.equal(
	hash,
	'#Bar',
);

Clone this wiki locally