Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array.

According to the documentation:

An array of MutationRecord objects, detailing each change that took place;

I'm looking for an example where mutationRecordList.length > 1

<h2 id="testNode" onclick="addTimeNode(this)">Click me!</h2>

<script>
  function addTimeNode(node) {
    const nodeP = document.createElement("p")
    const today = new Date()
    nodeP.innerText = [today.getHours(), today.getMinutes(), today.getSeconds()].join(":")
    node.append(nodeP)
  }

  (
    () => {
      window.onload = () => {
        const observer = new MutationObserver((mutationRecordList, observer)=>{
          if (mutationRecordList.length > 1){
            console.log("Thanks. This is what I want!") // 👈
          }
          console.log(observer.name)
          for(const mutation of mutationRecordList) {
            const target = mutation.target
            switch(mutation.type) {
              case "childList":
                console.log('A child node has been added or removed.')
                break
            }
            if (target.childNodes.length > 2) {
              observer.disconnect()
              console.log('disconnect observer')
            }
          }
        })
        observer.name = "test observer"
        observer.observe(document.getElementById('testNode'), {
          // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
          childList: true,
        })
      }
    }
  )()
</script>

Answer â„–1

Shoutout to @wOxxOm for the help! Here's a demonstration showcasing multiple DOM operations within the same event loop cycle.

<h2 id="testNode" onclick="addTimeNode(this)">Click me!</h2>

<script>
  function addTimeNode(node) {
    const nodeP = document.createElement("p")
    const nodeP2 = document.createElement("p")
    nodeP.className = "test-add"
    nodeP2.className = "test-delete"
    const today = new Date()
    nodeP.innerText = [today.getHours(), today.getMinutes(), today.getSeconds()].join(":")
    node.append(nodeP, nodeP2)
    node.querySelector(`p[class="test-delete"]`).remove()
  }

  (
    () => {
      window.onload = () => {
        const observer = new MutationObserver((mutationRecordList, observer)=>{
          if (mutationRecordList.length > 1){
            console.log(`This is exactly what I was looking for. length:${mutationRecordList.length}`) // 👈
          }
          console.log(observer.name)
          let i = 0
          for(const mutation of mutationRecordList) {
            console.log(`mutationRecordList[${i++}]`)
            const target = mutation.target
            switch(mutation.type) {
              case "childList":
                for (const node of mutation.addedNodes) {
                  console.log(`A child node has been added. className:${node.className}`)
                }

                for (const node of mutation.removedNodes) {
                  console.log(`A child node has been removed. className:${node.className}`)
                }
                break
            }
            if (target.childNodes.length > 2) {
              observer.disconnect()
              console.log('observer disconnected')
            }
          }
          console.log('----')
        })
        observer.name = "test observer"
        observer.observe(document.getElementById('testNode'), {
          // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
          childList: true,
        })
      }
    }
  )()
</script>

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

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...

Using $stateParams injection for unit testing Angular applications with Karma

Here is the starting point for the controller code: angular .module('hc.hotelContent') .controller('NameLocationController', nameLocationCtrlFn); //Todo change hotelDataService nameLocationCtrlFn.$inject = ['$stateParams', &a ...

Building with Webpack on a started Express server can be achieved by following these steps

Hello there, I am diving into the world of React and Webpack. My configuration in `webpack.config.js` looks like this: const webpack = require('webpack'); const path = require('path'); module.exports = { cache: true, entry: { ...

Error: Attempting to access 'defer' property of an undefined object in Angular JS WebSocket

I am relatively new to the world of web technologies, piecing together code snippets from various sources to create this code. My task involves retrieving data for a web application built on angularjs from a websocket using APIs. Below is the code snippe ...

Implement code to execute exclusively on the initial success of react-query

I have a unique scenario where I need to utilize standard useQuery behavior, while also executing a piece of code only on the initial onSuccess event. Although I understand that I can accomplish this using useRef, I am curious if there is an alternative a ...

Are node.js and AngularJS connected in any way?

Node.js relies on npm for package management, while AngularJS CLI also uses npm for its modules. Is there a connection between these two? I have installed Node.js and tested it with a simple 'hello.js' file containing just one line of code: con ...

Form submissions are not saving checkbox answers

As a beginner, I'm struggling to save the checkbox answers on the page after submission. The code below is quite lengthy (checkboxes start at 314). I have a feeling that I might be missing a piece of code, but I just can't seem to pinpoint what i ...

Sequelize encountered an error: getaddrinfo ENOTFOUND (even though the address is correct)

I've encountered some Sequelize errors while attempting to deploy a site I developed using Angular and Express/Sequelize. Here's the issue: Everything works perfectly on my local WAMP server, connecting to the local database without any problems ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

How can the backgroundImage css in react admin <Login /> be replaced using Material-UI?

I have been refering to the following resources: Learn about customizing login page background in React-Admin: Explore themes customization in Material-UI: https://material-ui.com/customization/components/ Instead of using a preset background, I want to ...

Issue with error handling not being triggered when calling SAPUI5 function()

IBAN validation within a SAPUI5 Wizard is causing some issues for me. I am utilizing a functionImport on a V2 ODataModel (sap.ui.model.odata.v2.ODataModel) to perform this validation. Despite receiving a 202 status code, the request actually failed. Here ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...

HTML table containing radio buttons styled with Font Awesome icons

I'm having some trouble getting a radio button with Font Awesome to work properly within an HTML table. Outside of the table, it functions as expected, but inside the table, it only seems to hide/show between the two states without displaying the chec ...

Experimenting with the speechSynthesis API within an iOS webview application

I'm currently working on developing an app that features TTS capabilities. Within my webview app (utilizing a React frontend compiled with Cordova, but considering transitioning to React Native), I am implementing the speechSynthesis API. It function ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

Update the multidimensional array function to ES6 syntax

I'm in the process of developing a function for my app and I'm curious if there's a more elegant way to implement it using ES6, without relying on two for loops. The goal is to create a multi-dimensional array that keeps track of x and y co ...

Displaying or concealing HTML elements using AngularJS while a modal is open

Looking for a way to display a loading spinner icon on my page when a user triggers a button that opens a modal, and then have the spinner disappear once the modal is open and its content has loaded. Currently, I've managed to make the spinner show up ...

a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...