diff --git a/src/wiki/util/findSectionHeading.ts b/src/wiki/util/findSectionHeading.ts new file mode 100644 index 00000000..105accef --- /dev/null +++ b/src/wiki/util/findSectionHeading.ts @@ -0,0 +1,26 @@ +/** + * Finds a MediaWiki section heading from the current DOM using its title. + * + * @param sectionHeadingName The name of the section to find. + * @param n The `n` of the section. Starts at 1. + * @return The found section heading. `null` if not found. + */ +export default function findSectionHeading( + sectionHeadingName: string, + n = 1 +): HTMLElement | null { + let currentN = 1; + + const headlines = Array.from( document.querySelectorAll( 'h2 > .mw-headline' ) ); + for ( const el of headlines ) { + if ( el instanceof HTMLElement && el.innerText === sectionHeadingName ) { + if ( currentN >= n ) { + return el.parentElement; + } else { + currentN++; + } + } + } + + return null; +} diff --git a/src/wiki/util/index.ts b/src/wiki/util/index.ts index f001cf34..8e691543 100644 --- a/src/wiki/util/index.ts +++ b/src/wiki/util/index.ts @@ -1,6 +1,7 @@ import decorateEditSummary from './decorateEditSummary'; import delink from './delink'; import errorToOO from './errorToOO'; +import findSectionHeading from './findSectionHeading'; import getApiErrorText from './getApiErrorText'; import getNativeRange from './getNativeRange'; import getPageContent from './getPageContent'; @@ -32,6 +33,7 @@ export default { decorateEditSummary: decorateEditSummary, delink: delink, errorToOO: errorToOO, + findSectionHeading: findSectionHeading, getApiErrorText: getApiErrorText, getNativeRange: getNativeRange, getPageContent: getPageContent,