How to wait until an element exists?

后端 未结 19 2070
广开言路
广开言路 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:35

    if you have async dom changes, this function checks (with time limit in seconds) for the DOM elements, it will not be heavy for the DOM and its Promise based :)

    function getElement(selector, i = 5) {
      return new Promise(async (resolve, reject) => {
        if(i <= 0) return reject(`${selector} not found`);
        const elements = document.querySelectorAll(selector);
        if(elements.length) return resolve(elements);
        return setTimeout(async () => await getElement(selector, i-1), 1000);
      })
    }
    
    // Now call it with your selector
    
    try {
      element = await getElement('.woohoo');
    } catch(e) { // catch the e }
    
    //OR
    
    getElement('.woohoo', 5)
    .then(element => { // do somthing with the elements })
    .catch(e => { // catch the error });
    

提交回复
热议问题