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

前端 未结 8 2022
别跟我提以往
别跟我提以往 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'));
    
    0 讨论(0)
  • 2020-11-22 17:09

    Check out this plugin that does exacly that - jquery.initialize

    It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them

    Initialize looks like this

    $(".some-element").initialize( function(){
        $(this).css("color", "blue");
    });
    

    But now if new element matching .some-element selector will appear on page, it will be instanty initialized.

    The way new item is added is not important, you dont need to care about any callbacks etc.

    So if you'd add new element like:

    $("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
    

    it will be instantly initialized.

    Plugin is based on MutationObserver

    0 讨论(0)
提交回复
热议问题