How do I monitor the DOM for changes?

前端 未结 4 1041
傲寒
傲寒 2020-11-28 13:53

Is there a way - using jQuery or otherwise - to monitor the DOM for insertions, deletions, updates to styles, etc?

相关标签:
4条回答
  • 2020-11-28 14:03

    See "MutationEvent" elements in here: https://developer.mozilla.org/en/DOM/DOM_event_reference but those are deprecated.

    jQuery now features a way to attach events to existing AND future elements corresponding to a selector: http://docs.jquery.com/Events/live#typefn

    It may be a trick you could use for lack of proper DOM Node modification info.

    0 讨论(0)
  • 2020-11-28 14:03

    See the mutation-summary library. It's built on top of a new browser API called DOM Mutation Observers.

    0 讨论(0)
  • 2020-11-28 14:15

    This is only for debugging purposes:

    Firebug currently allows setting breakpoints on html nodes.

    You have to open the html inspector, right click on a node and you have the following options:

    • Interrupt on attribute change
    • Interrupt on child add/remove
    • Interrupt on remove

    Once you reach the breakpoint you can also browse the call stack.

    Google Chrome has a similar feature too.

    0 讨论(0)
  • 2020-11-28 14:19

    I have recently written a plugin that does exactly that - jquery.initialize

    You use it the same way as .each function

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

    The difference from .each is - it takes your selector, in this case .some-element and wait for new elements with this selector in the future, if such element will be added, it will be initialized too.

    In our case initialize function just change element color to blue. So if we'll add new element (no matter if with ajax or even F12 inspector or anything) like:

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

    Plugin will init it instantly. Also plugin makes sure one element is initialized only once. So if you add element, then .deatch() it from body and then add it again, it will not be initialized again.

    $("<div/>").addClass('some-element').appendTo("body").detach()
        .appendTo(".some-container");
    //initialized only once
    

    Plugin is based on MutationObserver - it will work on IE9 and 10 with dependencies as detailed on the readme page.

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