How to wait until an element exists?

后端 未结 19 2175
广开言路
广开言路 2020-11-22 09:14

I\'m working on an Extension in Chrome, and I\'m wondering: what\'s the best way to find out when an element comes into existence? Using plain javascript, with an interval t

19条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 09:32

    This is a simple solution for those who are used to promises and don't want to use any third party libs or timers.

    I have been using it in my projects for a while

    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)) {
                    resolve(document.querySelector(selector));
                    observer.disconnect();
                }
            });
    
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        });
    }
    

    To use it:

    waitForElm('.some-class').then(elm => console.log(elm.textContent));
    

    or with async/await

    const elm = await waitForElm('.some-classs')
    

提交回复
热议问题