DOM : How to detect a new child elements?

前端 未结 3 1077
灰色年华
灰色年华 2020-12-16 18:11

I want to detect the insertion of a new div element only as a direct child of the parent div.

Example:

相关标签:
3条回答
  • 2020-12-16 18:47

    Assume your event handler looks like this:

    function(evt) {
        // whatever
    }
    

    Inside the handler, evt.relatedNode is the element into which the insertion is being performed. You can switch on it and decide to ignore or process the event.

    See it in action.

    0 讨论(0)
  • 2020-12-16 18:51

    Use DOMNodeInserted on the parent and check the event.target.parentNode of the added element. If its id is parent, then the element is a direct descendant.

    Demo: http://jsfiddle.net/ThinkingStiff/f2w7V/

    document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {
    
        if( event.target.parentNode.id == 'parent' ) {
            //direct descendant        
        };
    
    }, false );
    
    0 讨论(0)
  • 2020-12-16 18:52

    Why don't you use DOMNodeInserted, but add a check / if-statement in the event handler so the real logic only runs when you want it to?

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