Last updated: Apr 4, 2024
Reading time·7 min

If you need to detect when an element is
removedfrom the DOM, click on the second subheading.
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.
const box = document.createElement('div'); console.log(box.isConnected); // 👉️ false document.body.appendChild(box); console.log(box.isConnected); // 👉️ true
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.
<!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.
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);

The startObserving function takes 2 parameters:
domNode - the DOM node within which the child element will eventually be
inserted.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.
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'); } }); });
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.
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.
// ... 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.
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:
div element using document.createElement.my-class class to the element.innerHTML markup of the element.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.
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.
<!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>
And, here is the code for the index.js file.
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);

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.
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.
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.
if (elementAdded) { console.log('The element was added to the DOM'); }
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.
<!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>
And here is the related JavaScript code.
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();

The startObserving function takes 2 parameters:
domNode - the DOM node from which the child element will eventually be
removed.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.
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.
if (elementRemoved) { console.log('The element was removed from the DOM'); }
The last step is to call the MutationObserver.observe() method.
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.
// ... 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.
const parent = document.getElementById('parent'); startObserving(parent, 'child-class'); const child = document.querySelector('.child-class'); child.remove();
id.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.
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.
<!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>
And, here is the code for the index.js file.
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);

The code for the startObserving function remains unchanged.
However, this time, we passed the document.body element to the
startObserving() function.
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.
if (elementRemoved) { console.log('The element was removed from the DOM'); }

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