Monitor changes to DOM elements with JavaScript Mutation Observer

Recently, I've been experimenting with a Mutation Observer and using the following configuration:

config = { characterData: true, characterDataOldValue: true };

This is the structure of my HTML page:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script src="script.js"></script>
        <title>Test</title>
</head>
<body>
    <p id="test" contenteditable="true">Test<b>subtree</b>test</p>

Interestingly, the Mutation observer wasn't functioning as expected until I included 'subtree' in the config:

config = { characterData: true, subtree: true, characterDataOldValue: true };

I'm a bit puzzled as to why this is necessary. Any explanations?

Answer №1

Here is the mutation observer code that is functioning correctly. To pinpoint the exact issue, could you share more of your code? For additional details, you can refer to the following article: DOM MutationObserver – reacting to DOM changes without killing browser performance.

const targetNode = document.getElementById('test');
console.log(targetNode);

// Creating an observer instance linked to the callback function
const observer = new MutationObserver((mutationList, observer) => {
  console.log("working");
});

// Define options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// If needed, you can stop observing later
//observer.disconnect();
<p id="test" contenteditable="true">Test</p>

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

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

Tips on utilizing innerHTML or innerText to add content to the Evernote editor, a rich text editor

A method authored by Jayant was employed in this particular post how-to-insert-text-into-the-textarea-at-the-current-cursor-position to perform an insertion into the Evernote editor. The Evernote editor being a rich text editor, altering from el.value to ...

Managing User-Triggered Requests in Ajax and JavaScript

Currently experimenting with some Ajax code, I have created a scenario to illustrate my issue. I am reaching out to experts for a possible solution, thank you. Scenario: There is an HTML button as follows: <p onclick="ajax_call();">Click</p>. ...

Using Mongoose to calculate and retrieve the total sum of elements within an array

In the following schema, I have defined the structure: let postScheme = new Schema({ title: { type: String, required: true }, body: String, isImage: Boolean, imageUrl: String, icon: String, time: { type: ...

Error: The function styles$1.makeStyles is not defined

Currently, I am experimenting with rollup for bundling. However, when I run the code, I encounter the following problem: https://i.stack.imgur.com/8xLT3.png import { makeStyles } from '@material-ui/styles'; const styles = makeStyles({ subHead ...

Why do attributes of a directive fail to function within a different directive in AngularJS?

Trying to set attributes of the angularJS directive named ng-FitText within another angularJS directive called scroll-cards. Here's the approach I'm taking: In the code snippet below, the attribute data-fittest is being assigned from ng-FitText ...

The React hamburger menu triggers a re-render of child elements within the layout

I am currently working with React and Material UI v5. Within my layout, I have a menu component with children. Whenever I click on the menu, it triggers a refresh of the children components. I attempted to resolve this by encapsulating the child components ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

What is the best way to resize an element such as an image?

When an image is resized using a percentage, it preserves its aspect ratio properly. I am looking for a way to replicate this behavior with a div. My current challenge involves precisely positioning an element relative to an image. The image fills 100% of ...

When dragging a new connection in jsPlumb, the existing one should be automatically removed

After using jsPlumb, I was able to create a setup with the following features: Multiple nodes functioning like nodes in a unique flowchart design. Each node has a single target where connections can be dropped. Every node has zero, one, or more exits. Ea ...

Ensure that it is safe to bypass Vue's built-in sanitization on this specific Vue component for the href attribute

I encountered an issue with a .vue file that contains an anchor tag as shown below: <a class="login_class" :href="loginUrl">Use Universal Login</a> When running Sonar, it raises a warning regarding the :href attribute: En ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...

Arranging numbers in JavaScript lists

empList = [ { "Account": "AAA - 0029", "Available": "$100" }, { "Account": "BBB- 0146", "Available": "200" }, { "Account": "AAA - 1812", "Available": "300"}, { "Account": "CCC- 2019", "Available": "400"}, { "Account" ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

ajax ignores output from php

I've been working on passing PHP echo values through AJAX, but I've encountered a problem where the if and else conditions are being skipped in the success function of AJAX. Even when the if condition is met, the else statements are still being e ...

Having trouble switching states in React

Can anyone assist me with a code issue I'm facing when trying to run it onClick? The desired functionality is for each button to display the names set in the 'useState' state, which should then change to 'Click on close' when click ...

Text in SVG file misaligned at the edge

After creating an SVG with a base64 background image and two text areas for top and bottom texts, I encountered an issue on Internet Explorer and Edge. The problem is that the bottom text is aligned to the left instead of the center, and its position is in ...

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

Guidelines for centering 2 images with JavaScript

I am faced with a unique challenge involving 2 images, where one image has a designated Mask area and the other image is supposed to be visible through the Masked area of the first image. My goal is to align the second image in the center of the Mask area ...