Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo.

When the element with the classname foo is detected among the mutated objects, I want to trigger a function.

Here is my current implementation:

  mutations.forEach(mutation => {
    if (!mutation.addedNodes || mutation.addedNodes[0].className === undefined || mutation.addedNodes[0].className !== 'foo') {
      return;
    } else {
      console.log(mutation.addedNodes[0].className + ' has been loaded!');
    }
  });

This method technically works: the console log is displayed when all three conditions are met.

However, there are situations where mutation.addedNodes[0] does not contain any className data, resulting in the error message:

Cannot read property 'className' of undefined

I understand why this error occurs; sometimes mutations does not have an addedNodes[0] or it is indeed undefined. But I'm unsure about the best approach to only trigger the console log (eventually, my function) when all the above conditions are satisfied.

As I continue to learn ES6, I believe there might be a solution that could assist me here, but I'm having trouble finding the most effective way forward.

Answer №1

  1. When the page is loading, each node that is reported may have numerous nested nodes within it, requiring you to go through all the addedNodes and examine each one's tree.
  2. Some of the mutation records that are reported may involve nodes being removed (such as by a script on the page), in which case addedNodes will be an array with no elements.
  3. There could also be comments or text nodes among the added nodes, so those need to be ignored.

const matching = [];
for (const {addedNodes} of mutations) {
  for (const node of addedNodes) {
    if (node.nodeType !== Node.ELEMENT_NODE) {
      continue;
    }
    if (node.classList.contains(className)) {
      matching.push(node);
    }
    if (node.children[0]) {
      matching.push(...node.getElementsByClassName(className));
    }
  }
}
if (matching.length) console.log(matching);

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

I am puzzled as to why my ajax script is giving me a 404 error even though the URL appears to be correct

Even though it's not a cross-domain problem, Ajax is returning a 404 error code. In my TIZEN Web application project, I am trying to make an ajax request to a WebService that contains functions necessary for the project. Initially, the xhr.status was ...

How to enable the Copy to Clipboard feature for multiple buttons and transition from using an ID to a class identifier

Can someone please assist me? I have a copy to clipboard function that works well for IDs and a single button on my website. However, I need to modify it to work for multiple buttons and values with a class identifier. Unfortunately, I am unsure how to mak ...

React throwing error: Context value is undefined

Why is the Context value showing as undefined? The issue lies in src/Context.js: import React, { Component } from 'react'; const Context = React.createContext(); export class Provider extends Component { state = { a: 1, b: 2 }; render( ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

What steps can I take to minify my code using react-create-app?

Currently, I am facing an issue with minifying my code on the server. Despite running npm run build, which is supposed to handle all the minifying processes (as shown here: https://i.stack.imgur.com/wjpd7.png), I still see the unminified code when accessin ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

How can Angular JS detect the names of the CSS files being used in an HTML page?

I am in the process of developing a brand new widget where we are incorporating a unique feature that displays the number of CSS files included within an HTML page. Our team requires the count and names of all CSS files utilized on the webpage. While I a ...

Importing ES module into Next.js leads to ERR_REQUIRE_ESM

Encountered this issue while attempting to integrate ky into a Next.js project: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /foo/node_modules/ky/index.js It seems that the cause of this problem is Webpack (or Babel) converting all import ...

The React function is encountering a situation where the action payload is not

I encountered an error stating Cannot read property 'data' of undefined switch (action.type){ case REGISTER_USER: console.log("Action ", action);// This prints {type: "REGISTER_USER", payload: undefined} return [action.payload.data, ...

Load Vue 3 components dynamically using a string-based approach

Exploring ways to dynamically load components based on a string input. Here is an attempt at achieving this: <component v-for="component in components" :is="eval(component)" /> However, this approach does not yield the desired r ...

Exploring Firefox webpage data with JavaScript or browser extensions

Have you ever wondered if it's possible to retrieve the "Modified" information seen in Firefox when selecting "View page Info" by just using a JavaScript extension? ...

Ways to showcase the object on the console

How can I display the object function in the console? When I try, nothing is displayed. Can you please help me figure out what went wrong? I know I must have made a mistake somewhere, as this is my first question on Stack Overflow. import React, ...

Is it possible to convert a blob to an image file using the FileReader in HTML

client side code <head> <script> var reader = new FileReader(); var objVal; var image = new Image(); reader.onload = function(e) { document.getElementById('propertyImg').setAttribute('src', e.target.result); }; fun ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Implementing Node.js with browser cache and handling 304 responses

I am currently in the process of creating a single page application with a standard HTML layout as shown below: <html> <head> <title>...</title> <link rel="stylesheet" media="all" type="text/css" href="css/main.css"> ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Unable to save Ajax data in session array

Currently, I am developing a cart system using jquery, ajax, and php. The issue I am facing is that the text within the HTML elements is not being added to the session array. Below is the ajax code I am using: $(document).ready(function(){ $("#car ...

How can I display JSON data as key-value pairs in ReactJS?

Transitioning from JavaScript to React, I've come across some threads that touch on this topic but none quite hit the mark. I have a local JSON file that was created with a Python script, and it looks something like this: [{"hello": 10, "world": 15 ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...