An async implementation of getElementById that returns a promise and waits for the element to be added to the DOM if it's not already present. Supports timeouts and AbortController signals for flexible async DOM element handling.
- Promise-based: Clean async/await syntax
- Timeout support: Set custom timeouts or wait indefinitely
- Abortable: Cancel operations using AbortController
- MutationObserver: Efficiently watches for DOM changes
- TypeScript: Full TypeScript support with type definitions
- Lightweight: Minimal dependencies and small bundle size
npm install get-element-promise-by-idimport { getElementPromiseById } from 'get-element-promise-by-id';
// Wait for an element to appear
const element = await getElementPromiseById('my-element');
console.log('Element found:', element);// Wait up to 5 seconds for the element
try {
const element = await getElementPromiseById('my-element', { timeout: 5000 });
console.log('Element found:', element);
} catch (error) {
if (error.name === 'TimeoutError') {
console.log('Element not found within timeout');
}
}const controller = new AbortController();
// Start waiting for element
const promise = getElementPromiseById('my-element', {
signal: controller.signal
});
// Cancel after 3 seconds
setTimeout(() => controller.abort(), 3000);
try {
const element = await promise;
console.log('Element found:', element);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Operation was cancelled');
}
}Returns a promise that resolves when an element with the specified ID is found in the DOM.
id(string): The ID of the element to wait foroptions(object, optional):timeout(number, default: 0): Timeout in milliseconds. Set to 0 for no timeoutsignal(AbortSignal): AbortSignal to cancel the operation
Promise<HTMLElement>: Promise that resolves with the found element
DOMExceptionwith name'TimeoutError': When the timeout is reachedDOMExceptionwith name'AbortError': When the operation is aborted
Try the interactive demo at: https://tombigel.github.io/get-element-promise-by-id/
Or run it locally:
git clone https://github.com/tombigel/get-element-promise-by-id.git
cd get-element-promise-by-id
npm install
npm run dev# Install dependencies
npm install
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Run with coverage
npm run coverage
# Build library
npm run build:lib
# Build demo
npm run build:demo
# Start development server
npm run devThis library uses modern JavaScript features including:
- MutationObserver
- AbortController
- Promises
Supported in all modern browsers. For older browser support, ensure these APIs are polyfilled.
MIT
Contributions are welcome! Please feel free to submit a Pull Request.
Tom Bigelajzen
@tombigel