DOM : How to detect a new child elements?

前端 未结 3 1085
灰色年华
灰色年华 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: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 );
    

提交回复
热议问题