summaryrefslogtreecommitdiff
path: root/source/helpers/on-replaced-element.ts
blob: 12594a95209535d336ba49d5bb0d432e2e985b24 (plain) (blame)
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
import select from 'select-dom';

import onElementRemoval from './on-element-removal';

/**
Tracks the replacement of an element, identified via selector.

@param selector The unique selector used to find the element and its future replacements
@param callback The function to call after it's replaced
*/

export default async function onReplacedElement(selector: string, callback: VoidCallback): Promise<void> {
	let trackedElement = select(selector);
	if (!trackedElement) {
		throw new Error('The element can’t be found');
	}

	while (trackedElement) {
		// eslint-disable-next-line no-await-in-loop
		await onElementRemoval(trackedElement);
		trackedElement = select(selector);
		if (trackedElement) {
			callback();
		}
	}
}