Debian Codegraph @

src/modules/getAnchorElement.ts

raw
1 import { query } from '../utils.js';
2
3 /**
4 * Find the anchor element for a given hash.
5 *
6 * @param hash Hash with or without leading '#'
7 * @returns The element, if found, or null.
8 *
9 * @see https://html.spec.whatwg.org/#find-a-potential-indicated-element
10 */
11 export const getAnchorElement = (hash?: string): Element | null => {
12 if (hash && hash.charAt(0) === '#') {
13 hash = hash.substring(1);
14 }
15
16 if (!hash) {
17 return null;
18 }
19
20 const decoded = decodeURIComponent(hash);
21 let element =
22 document.getElementById(hash) ||
23 document.getElementById(decoded) ||
24 query(`a[name='${CSS.escape(hash)}']`) ||
25 query(`a[name='${CSS.escape(decoded)}']`);
26
27 if (!element && hash === 'top') {
28 element = document.body;
29 }
30
31 return element;
32 };