Home > Web Front-end > JS Tutorial > How Can I Efficiently Await Element Existence in JavaScript?

How Can I Efficiently Await Element Existence in JavaScript?

Barbara Streisand
Release: 2024-12-10 00:23:14
Original
564 people have browsed it

How Can I Efficiently Await Element Existence in JavaScript?

Await Element Existence with MutationObserver

As you've encountered in your Chrome extension development, it's crucial to know when an element becomes available on the page. While using intervals to check for its appearance is a common approach, it can be inefficient. Fortunately, jQuery doesn't provide a straightforward solution.

A modern and effective alternative is utilizing the MutationObserver API. This allows you to create a JavaScript function that listens for changes in the DOM tree:

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                observer.disconnect();
                resolve(document.querySelector(selector));
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}
Copy after login

This function takes a selector as input and returns a Promise that resolves when the element is found.

To use it, you can write:

waitForElm('.some-class').then((elm) => {
    console.log('Element is ready');
    console.log(elm.textContent);
});
Copy after login

Or, with async/await:

const elm = await waitForElm('.some-class');
Copy after login

The above is the detailed content of How Can I Efficiently Await Element Existence in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template