waitForElement.js Documentation
A utility library for waiting for elements to appear in the DOM. Provides reliable element detection with configurable timeout and retry options, supporting both single elements and multiple elements matching a selector.
Installation
Include the library in your HTML file:
<script src="path/to/waitForElement.js"></script>
Quick Start
Basic Usage
Wait for a single element document.querySelector to appear in the DOM:
waitForElement('#my-element').then(element => {
console.log('Element found:', element);
// Work with the element
}).catch(error => {
console.error(error);
});
Wait for multiple elements document.querySelectorAll:
waitForElement('.list-item', 500, 30, true).then(elements => {
console.log('Found elements:', elements.length);
// Process the NodeList
});
API Reference
waitForElement()
Waits for an element or elements matching the selector to appear in the DOM, checking at specified intervals until either the element is found or the maximum number of attempts is reached.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| selector | String | - | CSS selector for the element(s) to wait for (required) |
| duration | Number | 800 | Interval in milliseconds between checks (optional) |
| maxTries | Number | 20 | Maximum number of attempts before timing out (optional) |
| multiple | Boolean | false | If true, waits for multiple elements (returns NodeList). If
false, waits for single
element (returns Element) (optional) |
Returns
Promise that resolves with:
- When
multiple=false: The first matching Element - When
multiple=true: A NodeList of all matching elements
Rejects with an error message if the element(s) are not found within the specified attempts.
Example
// Wait for a single element with more aggressive checking
waitForElement('#dynamic-content', 200, 50).then(element => {
element.classList.add('loaded');
});
// Wait for multiple elements
waitForElement('.dynamic-items', 500, 30, true).then(items => {
items.forEach(item => processItem(item));
});
waitForPageLoad()
Waits for the DOM to be fully loaded or interactive. Returns a Promise that resolves when the page is ready.
Returns
Promise that resolves when the DOM is ready.
Example
waitForPageLoad().then(() => {
console.log('DOM is ready');
// Safe to query the DOM now
});
Note: This function is useful when you need to ensure the DOM is ready
before performing operations, similar to DOMContentLoaded event and
Tampermonkey's @run-at document-end but with
Promise interface.
Advanced Usage
Error Handling
Proper error handling for elements that might never appear:
waitForElement('#might-not-exist').then(element => {
// Success case
}).catch(error => {
console.warn('Element not critical, continuing...');
// Fallback behavior
});
Using with async/await
Cleaner syntax with async functions:
async function initialize() {
try {
await waitForPageLoad();
const form = await waitForElement('#user-form', 500, 30);
setupFormValidation(form);
} catch (error) {
console.error('Initialization failed:', error);
}
}
Examples
Waiting for Dynamic Content
Handling content loaded via AJAX or frameworks:
// After triggering a dynamic load
button.addEventListener('click', async () => {
loadDynamicContent();
try {
const newItems = await waitForElement('.new-content', 300, 40, true);
animateItems(newItems);
} catch {
showErrorMessage('Content failed to load');
}
});
See waitForElement in action with real-world scenarios