A small JavaScript function that executes a callback when elements matching a CSS selector appear in the DOM. It works with elements that are available on page load and dynamically added later.
// Basic usage
onElementFound({
selector: ".my-element",
callback: (element) => {
console.log("Element found!", element);
},
});
// Usage with custom timeout
onElementFound({
selector: "#dynamic-content",
callback: (element) => {
element.classList.add("processed");
},
timeout: 5000,
});
// Using additional options
onElementFound({
selector: ".product-card",
callback: (element) => {
initializeProductCard(element);
},
// Only observe direct children being added/removed (not attributes)
attributes: false,
childList: true,
subtree: false,
timeout: 15000,
});
// Wait for an element that signals the app is ready,
// then perform an unrelated action
onElementFound({
selector: ".app-initialized",
callback: () => {
// The element itself isn't used, but its presence
// indicates the app is ready for additional operations
// Load additional resources
loadSecondaryAssets();
},
});
onElementFound(options) Watches the DOM for elements matching a CSS selector and executes a callback when found. Automatically disconnects after finding the element or when timeout expires.
Parameters
Option | Type | Default | Description |
---|---|---|---|
selector | string | required | CSS selector to match (e.g. "#page-title", ".nav-menu", "h1") |
callback | Function | required | Function to call when element is found, receives the element as parameter |
timeout | number | 30000 |
Automatically disconnect after this many milliseconds (30 seconds by default) |
attributes | boolean | true |
Whether to observe attribute changes |
childList | boolean | true |
Whether to observe child elements |
subtree | boolean | true |
Whether to observe the entire subtree |
Returns: void
- The function doesn't return anything
Works in all modern browsers that support MutationObserver