How can I be notified when an element is added to the page?

前端 未结 8 2141
别跟我提以往
别跟我提以往 2020-11-22 16:11

I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I

8条回答
  •  一生所求
    2020-11-22 16:58

    A pure javascript solution (without jQuery):

    const SEARCH_DELAY = 100; // in ms
    
    // it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
    function waitForElementToBeAdded(cssSelector) {
      return new Promise((resolve) => {
        const interval = setInterval(() => {
          if (element = document.querySelector(cssSelector)) {
            clearInterval(interval);
            resolve(element);
          }
        }, SEARCH_DELAY);
      });
    }
    
    console.log(await waitForElementToBeAdded('#main'));
    

提交回复
热议问题