Yes, you can use the MutationObserver API in JavaScript to observe changes to elements with a specific class, such as 'comment'. The MutationObserver allows you to watch for changes in the DOM tree.
Here's how you can set up a MutationObserver to look for changes specifically in elements with the class 'comment':
// Function to handle changes in elements
function handleMutations(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
// Check added nodes for elements with the 'comment' class
mutation.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('comment')) {
console.log('A new comment element was added:', node);
}
});
// Check removed nodes for elements with the 'comment' class
mutation.removedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('comment')) {
console.log('A comment element was removed:', node);
}
});
}
// Optionally handle other types of mutations, like attributes or subtree
if (mutation.type === 'attributes' && mutation.target.classList.contains('comment')) {
console.log('Attributes changed on a comment element:', mutation.target);
}
}
}
// Specify what to observe
const config = {
childList: true, // Watch for additions or removals of child elements
attributes: true, // Monitor attribute changes
subtree: true // Allow monitoring of the target node and its descendants
};
// Select the node that will be observed for mutations
const targetNode = document.body; // You can specify a more specific target if needed
// Create an observer instance and pass the callback function
const observer = new MutationObserver(handleMutations);
// Start observing the target node with the specified configuration
observer.observe(targetNode, config);
// To stop observing, you can use:
// observer.disconnect();
Key Points:
-
targetNode: You specify the target node you want to observe. By using document.body, the observer watches the entire document, but you can target more specific elements.
-
config: You define what you want to observe, such as node additions/removals (childList), attribute changes (attributes), and whether to observe subtree changes (subtree).
-
handleMutations function: This processes the mutations. Here, nodes are checked if they are elements with the class 'comment'.
You can adjust the configuration and target node according to your specific needs.