Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach?

new MutationObserver(mut => {
    removed_nodes = removed_nodes(mut);
    console.log(removed_nodes.querySelectorAll('.hello'));
    console.log(removed_nodes.querySelectorAll('.myclass #a'));
}).observe(document.querySelector("html"), { childList: true, subtree: true });

Below is a sample code snippet specifically for filtering removed nodes by classes:

selected_classes = {"banana": 0, "hello": 0};

new MutationObserver(mut => {
    for (m of mut) {
        for (n of m.removedNodes) {
            if (n.classList)   // text node don't have a classList!
                for (c of n.classList.values())
                    if (c in selected_classes)
                        console.log("selected_classes found:", n);
            if (n.childNodes)
                for (n2 of n.childNodes.values())
                    if (n2.classList)
                        for (c of n2.classList.values())
                            if (c in selected_classes)
                                console.log("selected_classes found:", n2);                
        }
    }
}).observe(document.querySelector("html"), { childList: true, subtree: true });

document.getElementById("c").onclick = () => { document.getElementById("b").remove(); }
<div id="a">a</div>
<div id="b" class="tomato">b
<div id="b1">b1</div>
<div id="b2" class="hello">b2 (class hello)</div>
</div>
<div id="c">Click to remove b</div>

Answer №1

Utilize the CSS selector generated from selected_classes and integrate it with .matches() as well as .querySelectorAll() to retrieve corresponding notes

const selector = ".apple, .world";

new MutationObserver(mut => {
 
  for (m of mut) {
    for (n of m.removedNodes) {
      if (n.matches(selector)) {
        console.log("matched directly", n);
      }

      n.querySelectorAll(selector)
         .forEach(c => console.log("child (all levels)", c));
    }
  }
}).observe(document.querySelector("html"), { childList: true, subtree: true });

document.getElementById("c").onclick = () => { document.getElementById("b").remove(); }
<div id="a">a</div>
<div id="b" class="tomato">b
  <div id="b1">b1</div>
  <div id="b2" class="hello">b2 (class hello)</div>
  <div>
    <div>
      <div class="banana">Banana</div>
    </div>
  </div>
</div>
<div id="c">Click to eliminate b</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring GLTF models with Threejs - just a click away!

I am currently developing a project in three.js where I aim to load a GLTF file consisting of geometric shapes. My goal is to extract information, specifically the name, of the shapes that are clicked within the GLTF file. At this stage, I am using console ...

Ways to include text underneath icons using HTML and CSS

Seeking guidance on how to display text below icons on my website. Can someone please provide instructions? <div class="bottom-bar div-only-mobile" style="position: fixed; bottom: 0; width:100%"> <a href="Dashboard"> <ion-icon name= ...

In Javascript, have an audio clip play every 30 seconds

My webpage has a unique feature - it automatically plays a short audio clip as soon as the page loads. This functionality is achieved using a special audio player called nifty player. Here is the code snippet for embedding the player: <object classid= ...

What is the best way to establish a two-way connection between two arrays?

Within my application, there is an ItemsService responsible for fetching Items from the server and storing them as JSON objects in its cache. These Items may be displayed in various formats such as tables, graphs, or charts. For instance, when setting up ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

In mobile view, the grid text should be positioned on top of the input field

Created a basic grid layout with input fields. Everything looks fine on the PC, but on mobile devices, long text causes the input field to be positioned below the text. However, when the text is short like Lor, it appears next to the input field... I want ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

The worth of the scope is evident, yet it remains undefined when trying to access it

Currently, I am in the process of developing an AngularJS directive. However, I have encountered an issue where a scope variable appears to be undefined when attempting to access it. Interestingly, upon printing out the scope, it is evident that the variab ...

Is it possible to swap out the content within a <div> element with an external piece of HTML code using JQuery or JavaScript whenever the viewport dimensions are adjusted?

<html> <head> </head> function () { var viewportWidth = $(window).width(); if (viewportWidth < 700) { $('#wrapper').load('A.html'); }; <body> &l ...

Partial view encountering Dropzone JS function error

I am currently using jquery-modal by Kyle Fox and I've run into a problem. Whenever I try to open the modal window, my partial view gets loaded into it. However, I keep seeing this error in the console: Dropzone.options.dropzone is not recognized a ...

Viewing a PDF within a MUI tooltip

Currently, I am facing an issue where I am attempting to show a preview of a PDF file inside a Material-UI (MUI) Tooltip when a user hovers over a MUI ListItem. While I have successfully displayed previews of PNG and JPG files using Next.js' Image com ...

Issue arises when Protractor is unable to compare a variable with a web element due to unresolved promises

My strategy for this examination was to extract the inner text of an element, modify it, and then verify that the change had taken place by comparing the element with the variable. var fixedValue = element(by.xpath('/html/body/section/div/section/sec ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

Use the ng-repeat directive to display multiple items and let the user input a quantity for each item. Then, in AngularJs, gather all the form data, including the repeated items and their quantities, and

Hey there! I have a question related to AngularJs: How can I repeat pre-selected items using (ng-repeat) and allow users to enter a quantity for each item in a subsequent step, then submit all the form data? I'm wondering if adding $index to the repe ...

Guide on how to show the index value of an array on the console in Angular 2

Is there a way to show the array index value in the console window upon clicking the button inside the carousel component? The console seems to be displaying the index value twice and then redirecting back to the first array index value. Can we make it so ...

Firefox is having trouble keeping <select> tags within their designated borders

I am currently developing a mobile app that requires the use of 3 <select> elements stacked on top of each other. It is crucial for these tags to align perfectly with each other and not extend beyond the boundaries of the background div. I have manag ...

Trouble encountered while creating a table with the Bootstrap grid system

I'm attempting to create a table using the bootstrap grid system. The HTML code below is meant to generate the table, but I'm encountering an issue where the table cells overlap on screens with a width of 768px. .row.header { height: 44px; ...

execute the function after the animation has finished

Is it possible to trigger a function once an animation is complete using jQuery? Here's the code I'm working with: $('html, body').animate({scrollTop:$("body > .addAccountForm1").offset().top }, 'slow'); I want to execut ...

Steps for selectively extracting objects from an array containing nested objectsNeed a way to isolate specific objects

Currently, I am working on a project in JavaScript and have created an array called folders that holds multiple objects: folders = [folder1, folder2, folder3...] Each object within the array has various properties, one of which is docs that is an array o ...

Having trouble with the functionality of JQuery drop feature?

As I delve into implementing drag and drop functionality with JQuery, I encounter a peculiar issue. I have set up 3 'draggable' divs and corresponding 3 'droppable' divs. The intended behavior is for each draggable element to be accepte ...