How to wait until an element exists?

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

    For a simple approach using jQuery I've found this to work well:

      // Wait for element to exist.
      function elementLoaded(el, cb) {
        if ($(el).length) {
          // Element is now loaded.
          cb($(el));
        } else {
          // Repeat every 500ms.
          setTimeout(function() {
            elementLoaded(el, cb)
          }, 500);
        }
      };
    
      elementLoaded('.element-selector', function(el) {
        // Element is ready to use.
        el.click(function() {
          alert("You just clicked a dynamically inserted element");
        });
      });
    

    Here we simply check every 500ms to see whether the element is loaded, when it is, we can use it.

    This is especially useful for adding click handlers to elements which have been dynamically added to the document.

提交回复
热议问题