MutationObserver in C# for HTML DOM Changes

MutationObserver watches changes in the DOM tree and calls a callback after matching mutations occur. In Aspose.HTML for .NET, the MutationObserver class can observe inserted nodes, removed nodes, text changes, and attribute changes in an HTMLDocument.

To observe DOM changes in C#, create an HTMLDocument, create a MutationObserver with a callback, configure MutationObserverInit, call Observe(target, options), and then modify the DOM. The callback receives mutation records that describe what changed.

Use this API when your application needs to react to document updates during HTML processing, automation, validation, or dynamic content generation.

What Is MutationObserver?

Mutation Observer is a DOM mechanism that watches changes in a document tree and calls a callback function when matching changes are detected. Watching changes in the DOM tree is periodically necessary for complex web applications and frameworks. With MutationObserver, you can monitor changes to a document’s specific nodes, attributes, child elements, or text content and execute custom logic in response.

In Aspose.HTML for .NET, document observation is represented by MutationObserver. The observer is configurable, so you can decide whether to watch direct children, descendants, attributes, or character data.

How to Use MutationObserver in C#

The following example demonstrates how to observe DOM changes caused by adding new nodes to an HTML document.

  1. Create an HTMLDocument instance.
  2. Create a MutationObserver object and pass a callback that receives mutation records and the observer.
  3. Create a MutationObserverInit object to configure which changes should be observed.
  4. Set options such as ChildList, Subtree, or CharacterData depending on the changes you need to detect.
  5. Call Observe(target, options) with the target node and observer configuration.
  6. Modify the DOM with methods such as CreateElement(), CreateTextNode(), and AppendChild().
  7. Inspect the mutation records in the callback after the DOM changes are completed.

The example uses these options:

If you are observing a node for changes, the callback is not fired until the DOM has finished the matching change. This behavior replaces older DOM Mutation Events and avoids the performance problems of firing synchronous events for every small mutation.

 1// Use Mutation Observer to watch for new nodes added to a document with C#
 2
 3// Create an empty HTML document
 4using (HTMLDocument document = new HTMLDocument())
 5{
 6    // Create a mutation observer instance
 7    Html.Dom.Mutations.MutationObserver observer = new Html.Dom.Mutations.MutationObserver((mutations, mutationObserver) =>
 8    {
 9        foreach (MutationRecord record in mutations)
10        {
11            foreach (Node node in record.AddedNodes)
12            {
13                Console.WriteLine("The '" + node + "' node was added to the document.");
14            }
15        }
16    });
17
18    // Configuration of the observer
19    MutationObserverInit config = new Html.Dom.Mutations.MutationObserverInit
20    {
21        ChildList = true,
22        Subtree = true,
23        CharacterData = true
24    };
25
26    // Pass in the target node to observe with the specified configuration
27    observer.Observe(document.Body, config);
28
29    // Now, we are going to modify DOM tree to check
30    // Create a paragraph element and append it to the document body
31    Element p = document.CreateElement("p");
32    document.Body.AppendChild(p);
33
34    // Create a text and append it to the paragraph
35    Text text = document.CreateTextNode("Hello, World");
36    p.AppendChild(text);
37
38    Console.WriteLine("Waiting for mutation. Press any key to continue...");
39    Output.ToString();
40}

Common MutationObserver Issues

IssueCauseFix
The callback is not calledThe observer options do not match the type of DOM change.Enable the relevant option, such as ChildList, Subtree, Attributes, or CharacterData, before calling Observe().
Changes inside nested elements are missedOnly direct children are being observed.Set Subtree = true when changes in descendants should be reported.
Text changes are not reportedCharacter data changes are not enabled.Set CharacterData = true when text node updates should be observed.
Too many records are producedThe observed target is too broad or too many mutation types are enabled.Observe the smallest useful node and enable only the mutation types required by the workflow.

FAQ

What does MutationObserver do in Aspose.HTML for .NET?

It watches a DOM node and reports matching changes through a callback, such as added nodes, removed nodes, attribute changes, or text changes.

Which node should I observe?

Observe the smallest node that covers your workflow. Use document.Body for body-level changes, or a specific element when only one section of the document matters.

Can MutationObserver detect changes in child elements?

Yes. Use ChildList = true for direct child changes and Subtree = true when descendant changes should also be observed.

Related Articles