iLiA
iLiA

Reputation: 3153

JS/JQuery: Detect when child element is added to parent

I have parent div where child elements are added dynamically and i need to detect when child is added. I heard about mutation observer which is new version of DOMSubTreeModified event, but are there better alternatives?

for example

$('div').//event = () => {
  //do stuff
}

Thanks You!

Upvotes: 0

Views: 3475

Answers (1)

Ange Loron
Ange Loron

Reputation: 1203

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

document.getElementById( 'parent' ).addEventListener( 'DOMNodeInserted', function ( event ) {
   if( event.target.parentNode.id === 'parent' ) {
       //direct descendant        
   };
}, false );

Credit goes to ThinkingStiff who already answered that question

Upvotes: 3

Related Questions