generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdomTools.ts
47 lines (43 loc) · 1.28 KB
/
domTools.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const findChildHeading = (node: HTMLElement): string | null => {
let headingText = null;
if (!node.querySelectorAll) return headingText;
const list: NodeList = node.querySelectorAll('[data-heading]');
if (list.length > 0) {
headingText = ((list[list.length - 1] as HTMLElement).attributes as any)['data-heading'].value;
}
return headingText;
}
/**
* Recursively goes up sibling element looking for a heading attribute
*
* @param node r
* @returns
*/
const findSiblingHeading = (node: HTMLElement): string | null => {
let headingText = null;
if (node.previousSibling) {
headingText = findChildHeading(node.previousSibling as HTMLElement);
if (!headingText) {
headingText = findSiblingHeading(node.previousSibling as HTMLElement);
}
}
return headingText
}
/**
* Recursively looks at sibling element and then works up the DOM tree (to parent) looking for an element with data-heading attribute
* @param node
* @returns
*/
export const getClosetHeading = (node: HTMLElement): string | null => {
let heading = null;
if (!node) return null;
// First look at siblins
if (node.previousSibling) {
heading = findSiblingHeading(node);
}
if (heading === null) {
heading = getClosetHeading(node.parentNode as HTMLElement);
}
// then look at parents.
return heading;
}