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

前端 未结 8 2143
别跟我提以往
别跟我提以往 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 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:

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

    it will be instantly initialized.

    Plugin is based on MutationObserver

提交回复
热议问题