Detect the appearance of an element in the browser DOM
- Promise API
- Driven by
MutationObserver
- Detect by
querySelecrtor
If the target element already exists when execution of "wait-element", it immediately resolve
and return the element.
$ npm install @1natsu/wait-element
import {waitElement, waitDisappearElement} from '@1natsu/wait-element';
(async () => {
const el = await waitElement('.late-comming');
console.log(el);
//=> example: "<div class="late-comming">I'm late</div>"
})();
(async () => {
const parent = await waitElement('#parent');
const el = await waitElement('.late-comming', { target: parent });
console.log(el);
//=> example: "<div class="late-comming">I'm late</div>"
})();
(async () => {
const el = await waitElement('.late-comming', { timeout: 5000 }).catch(err => console.log(err));
console.log(el);
//=> If detected element: "<div class="late-comming">I'm late</div>"
//=> If timeouted: Error: Element was not found: '.late-coming'
})();
(async () => {
let el;
try {
el = waitElement('.late-comming');
if (!isCondition) el.cancel();
} catch {
// some handling...
}
})();
(async () => {
const el = await waitDisappearElement('.will-disappear');
// disappeared the element from dom tree
console.log(el);
//=> example: null
})();
waitElement
& waitDisappearElement
is same api. Difference is waiting element for appear or disappear.
Type: string
Format is CSS-selector
Type: HTMLElement
Default: document
Specify a parent node (specify MutationObserve target).
When you know the parent node of the element you want to detect.
- Please also refer to the MutationObserver
Type: number
Default: 0
Unit: ms(Millisecond)
There is no timeout by default.
Type: MutationObserverInit
Default:
{
childList: true,
subtree: true,
attributes: true,
}
passed configs is merged with default configs.
Type: Function
Stop waiting for the element. Cancellation is synchronous.
Based on p-cancelable. Appreciate it.
The very similar library.
- element-ready
- Implementation method is different from this library.
MIT © 1natsu172