Detect when Element is added/removed from the DOM using JS

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
7 min

banner

# Table of Contents

  1. Detect when an Element is added to the DOM using JavaScript
  2. Detect when an Element is removed from the DOM using JavaScript

If you need to detect when an element is removed from the DOM, click on the second subheading.

# Detect when an Element is added to the DOM using JavaScript

If you simply need to check if an element is attached to the DOM, use the isConnected property.

The isConnected property returns true if the element is connected to the Document object and false otherwise.

index.js
const box = document.createElement('div'); console.log(box.isConnected); // 👉️ false document.body.appendChild(box); console.log(box.isConnected); // 👉️ true
The code for this article is available on GitHub

We used the document.createElement() method to create a div element.

The element is not yet attached to the DOM, so the isConnected property returned false.

We then called the appendChild() method to add the element to the DOM.

The isConnected property returns true once the element is connected to the Document object.

If you need to detect when an element is added to the DOM, use the MutationObserver API.

The MutationObserver() constructor creates and returns an observer object that invokes a given callback function when the specified DOM events occur (e.g. adding elements to the DOM).

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div>bobbyhadz.com</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const startObserving = (domNode, classToLookFor) => { const observer = new MutationObserver(mutations => { mutations.forEach(function (mutation) { console.log(Array.from(mutation.addedNodes)); const elementAdded = Array.from(mutation.addedNodes).some( element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } }, ); if (elementAdded) { console.log('The element was added to the DOM'); } }); }); observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, }); return observer; }; startObserving(document.body, 'my-class'); const newElement = document.createElement('div'); newElement.classList.add('my-class'); newElement.innerHTML = '<p>bobbyhadz.<span style="color: red;">com</span></p>'; document.body.appendChild(newElement);

detect when element is aded to the dom

The code for this article is available on GitHub

The startObserving function takes 2 parameters:

  1. domNode - the DOM node within which the child element will eventually be inserted.
  2. classToLookFor - the class name of the element that is expected to be added to the DOM.

We first used the MutationObserver() constructor to create an observer that invokes a callback function when specific DOM events occur.

The MutationObserver.addedNodes property returns a NodeList containing the nodes that were added to the target of the mutation observer.

We used the Array.some() method to iterate over the nodes.

index.js
const observer = new MutationObserver(mutations => { mutations.forEach(function (mutation) { console.log(Array.from(mutation.addedNodes)); const elementAdded = Array.from(mutation.addedNodes).some( element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } }, ); if (elementAdded) { console.log('The element was added to the DOM'); } }); });
The code for this article is available on GitHub

On each iteration, we check if the current node contains the classList property (text nodes don't contain the classList property).

If the condition is met, we use the classList.contains() method to check if the element contains the given class.

The Array.some() method will return true if at least one element with the specified class exists in the array of added elements.

The last step is to call the MutationObserver.observe() method.

index.js
observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, });

The method configures the MutationObserver callback to begin receiving notifications of changes to the DOM that match the specified options.

Here is an example that uses an if statement to check if the type of the event that triggered the callback function is the childList event.

index.js
// ... mutations.forEach(function (mutation) { if (mutation.type === 'childList') { console.log('child node is added or removed'); } }); // ...

If the childList event triggered the callback function, then a child node is added or removed.

The last step is to call the startObserving() function.

index.js
startObserving(document.body, 'my-class'); const newElement = document.createElement('div'); newElement.classList.add('my-class'); newElement.innerHTML = '<p>bobbyhadz.<span style="color: red;">com</span></p>'; document.body.appendChild(newElement);

We passed the document.body element as the first argument to the startObserving() function and a class of my-class.

We then:

  1. Created a div element using document.createElement.
  2. Used the classList.add() method to add the my-class class to the element.
  3. Set the innerHTML markup of the element.
  4. Added the element to the DOM using appendChild().

Once an element with a class of my-class is added to the DOM as a direct child of the document.body element, the MutationObserver notifies us by running the code in the if statement.

index.js
if (elementAdded) { console.log('The element was added to the DOM'); }

Here is an example that demonstrates how the MutationObserver works with a parent element and a direct child element.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div id="parent"></div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And, here is the code for the index.js file.

index.js
const startObserving = (domNode, classToLookFor) => { const observer = new MutationObserver(mutations => { mutations.forEach(function (mutation) { console.log(Array.from(mutation.addedNodes)); const elementAdded = Array.from(mutation.addedNodes).some( element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } }, ); if (elementAdded) { console.log('The element was added to the DOM'); } }); }); observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, }); return observer; }; const parent = document.getElementById('parent'); startObserving(parent, 'my-class'); const child = document.createElement('div'); child.classList.add('my-class'); child.innerHTML = '<p>bobbyhadz.<span style="color: red;">com</span></p>'; parent.appendChild(child);

detect element added to dom with parent and child

The code for this article is available on GitHub

The code for the startObserving() function remains the same.

The function takes a DOM node and a class to look for when child elements are added to the DOM node.

We selected the parent div by its id and passed it to the startObserving() function.

index.js
const parent = document.getElementById('parent'); startObserving(parent, 'my-class');

We then created the child element, added the my-class class to it appended it to the parent.

index.js
const child = document.createElement('div'); child.classList.add('my-class'); child.innerHTML = '<p>bobbyhadz.<span style="color: red;">com</span></p>'; parent.appendChild(child);

Note that the child element must be added as a direct child to the parent element for the following if block to run.

index.js
if (elementAdded) { console.log('The element was added to the DOM'); }

# Detect when an Element is removed from the DOM using JavaScript

If you need to detect when an element is removed from the DOM, use the MutationObserver API.

The MutationObserver() constructor creates and returns an observer object that invokes a given callback function when the specified DOM events occur (e.g. removing elements from the DOM).

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div id="parent"> <div class="child-class">Child 1</div> </div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const startObserving = (domNode, classToLookFor) => { const observer = new MutationObserver(mutations => { mutations.forEach(function (mutation) { console.log(Array.from(mutation.addedNodes)); const elementRemoved = Array.from( mutation.removedNodes, ).some(element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } }); if (elementRemoved) { console.log('The element was removed from the DOM'); } }); }); observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, }); return observer; }; const parent = document.getElementById('parent'); startObserving(parent, 'child-class'); const child = document.querySelector('.child-class'); child.remove();

detect when element is removed from dom

The code for this article is available on GitHub

The startObserving function takes 2 parameters:

  1. domNode - the DOM node from which the child element will eventually be removed.
  2. classToLookFor - the class name of the element that is expected to be removed from the DOM.

We first used the MutationObserver() constructor to create an observer that invokes a callback function when specific DOM events occur.

The MutationObserver.removedNodes property returns a NodeList containing the nodes that were removed from the target of the mutation observer.

We used the Array.some() method to iterate over the nodes.

index.js
const elementRemoved = Array.from( mutation.removedNodes, ).some(element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } });

On each iteration, we check if the current node contains the classList property (text nodes don't contain the classList property).

If the condition is met, we use the classList.contains() method to check if the element contains the given class.

The Array.some() method will return true if at least one element with the specified class exists in the array of removed elements.

If the condition is met, the if block is run.

index.js
if (elementRemoved) { console.log('The element was removed from the DOM'); }

The last step is to call the MutationObserver.observe() method.

index.js
observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, });
The code for this article is available on GitHub

The method configures the MutationObserver callback to begin receiving notifications of changes to the DOM that match the specified options.

Here is an example that uses an if statement to check if the type of the event that triggered the callback function is the childList event.

index.js
// ... mutations.forEach(function (mutation) { if (mutation.type === 'childList') { console.log('child node is added or removed'); } }); // ...

If the childList event triggered the callback function, then a child node is added or removed.

The last step is to call the startObserving() function.

index.js
const parent = document.getElementById('parent'); startObserving(parent, 'child-class'); const child = document.querySelector('.child-class'); child.remove();
  1. We selected the parent element by its id.
  2. We called the startObserving function with the parent element and the class child-class. This is the class of the element that is expected to be removed from the DOM.

The last step is to select the child and remove it from the DOM.

If you open the Console tab in your developer tools, you will see that the code in the following if statement is run.

index.js
if (elementRemoved) { console.log('The element was removed from the DOM'); }

Here is another example of using the MutationObserver API to detect when an element is removed.

This time, we'll detect when a direct child of the document.body element is removed.

Here is the updated HTML code.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <style> body { margin: 100px; } </style> </head> <body> <div class="container">bobbyhadz.com</div> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And, here is the code for the index.js file.

index.js
const startObserving = (domNode, classToLookFor) => { const observer = new MutationObserver(mutations => { mutations.forEach(function (mutation) { console.log(Array.from(mutation.addedNodes)); const elementRemoved = Array.from( mutation.removedNodes, ).some(element => { if (element.classList) { return element.classList.contains(classToLookFor); } else { return false; } }); if (elementRemoved) { console.log('The element was removed from the DOM'); } }); }); observer.observe(domNode, { childList: true, attributes: true, characterData: true, subtree: true, }); return observer; }; startObserving(document.body, 'container'); const containerElement = document.querySelector('.container'); document.body.removeChild(containerElement);

detect when element is removed from dom body

The code for this article is available on GitHub

The code for the startObserving function remains unchanged.

However, this time, we passed the document.body element to the startObserving() function.

index.js
startObserving(document.body, 'container'); const containerElement = document.querySelector('.container'); document.body.removeChild(containerElement);

We passed a class of container to the function. This is the class of the element that is expected to be removed from the DOM.

The last step is to select the DOM element and remove it from the DOM to test the Mutation Observer.

If you open the Console tab in your browser's developer tools, you will see that the code in the following if statement runs.

index.js
if (elementRemoved) { console.log('The element was removed from the DOM'); }

detect when element is removed from dom body

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.