@1natsu/wait-element

Detect the appearance of an element in the browser DOM

Usage no npm install needed!

<script type="module">
  import 1natsuWaitElement from 'https://cdn.skypack.dev/@1natsu/wait-element';
</script>

README

wait-element

Travis (.org) npm npm bundle size (minified) npm bundle size (minified + gzip)

Detect the appearance of an element in the browser DOM

a.k.a promise-querySelector

  • 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.

Install

$ npm install @1natsu/wait-element

Usage

Module specifiers

import {waitElement, waitDisappearElement} from '@1natsu/wait-element';

Basically

(async () => {
  const el = await waitElement('.late-comming');
  console.log(el);
  //=> example: "<div class="late-comming">I'm late</div>"
})();

When specify a parent element (specify MutationObserve target)

(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>"
})();

When setting timeout

(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'
})();

When cancel wait-element

(async () => {
  let el;

  try {
    el = waitElement('.late-comming');
    if (!isCondition) el.cancel();
  } catch {
    // some handling...
  }
})();

Wait for the element to disappear

(async () => {
    const el = await waitDisappearElement('.will-disappear');
    // disappeared the element from dom tree
  console.log(el);
  //=> example: null
})();

API

waitElement(selector, [options])

waitDisappearElement(selector, [options])

waitElement & waitDisappearElement is same api. Difference is waiting element for appear or disappear.

selector

Type: string

Format is CSS-selector

options

target

Type: HTMLElement
Default: document

Specify a parent node (specify MutationObserve target).

When you know the parent node of the element you want to detect.

timeout

Type: number
Default: 0
Unit: ms(Millisecond)

There is no timeout by default.

waitElement#cancel()

Type: Function

Stop waiting for the element. Cancellation is synchronous.

Based on p-cancelable. Appreciate it.

Similar

The very similar library.

  • element-ready
    • Implementation method is different from this library.

License

MIT © 1natsu172