Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Discover the Power of JavaScript MutationObserver!💪🚀
Dharmendra Kumar
Dharmendra Kumar

Posted on

     

Discover the Power of JavaScript MutationObserver!💪🚀

A Comprehensive Guide to Monitoring DOM Changes

TheMutationObserver API in JavaScript offers a powerful way to observe and react to changes in the DOM tree. Whether you're watching for updates to child elements, attributes, or even the text content within nodes, MutationObserver can help you handle these changes efficiently.


Introduction to MutationObserver

What is MutationObserver?

TheMutationObserver API allows you to monitor changes in the DOM tree. Whenever there's a modification, a specified callback function gets executed, enabling you to react dynamically to these changes.

How to Use MutationObserver

  1. Define a Callback Function:
functioncallback(mutations){mutations.forEach(mutation=>{console.log(mutation);});}
Enter fullscreen modeExit fullscreen mode
  1. Create a MutationObserver Object:
letobserver=newMutationObserver(callback);
Enter fullscreen modeExit fullscreen mode
  1. Start Observing DOM Changes:
observer.observe(targetNode,{childList:true,attributes:true});
Enter fullscreen modeExit fullscreen mode
  1. Stop Observing DOM Changes:
observer.disconnect();
Enter fullscreen modeExit fullscreen mode

Constructor: Creating a MutationObserver

MutationObserver()

To create a newMutationObserver instance, pass your callback function to theMutationObserver constructor:

letobserver=newMutationObserver(callback);
Enter fullscreen modeExit fullscreen mode

Example:

functionlogChanges(mutations){mutations.forEach(mutation=>{console.log(mutation);});}letobserver=newMutationObserver(logChanges);
Enter fullscreen modeExit fullscreen mode

Instance Methods: Controlling Your Observer

disconnect()

Thedisconnect() method stops the MutationObserver from receiving notifications of DOM changes. This can be useful when you no longer need to monitor the DOM or to improve performance.

Example:

observer.disconnect();
Enter fullscreen modeExit fullscreen mode

observe()

Theobserve() method starts the MutationObserver instance, allowing it to monitor a specified DOM node and its subtree.

Example:

observer.observe(targetNode,{childList:true,attributes:true,subtree:true,});
Enter fullscreen modeExit fullscreen mode

takeRecords()

ThetakeRecords() method returns an array of all the mutation records that have been detected but not yet processed by the callback.

Example:

letrecords=observer.takeRecords();records.forEach(record=>{console.log(record);});
Enter fullscreen modeExit fullscreen mode

Practical Examples

Observing Child Element Changes

HTML:

<ulid="language"><li>HTML</li><li>CSS</li><li>JavaScript</li></ul><buttonid="btnAdd">Add</button><buttonid="btnRemove">Remove</button>
Enter fullscreen modeExit fullscreen mode

JavaScript:

letlist=document.querySelector('#language');letbtnAdd=document.querySelector('#btnAdd');letbtnRemove=document.querySelector('#btnRemove');functionlog(mutations){mutations.forEach(mutation=>{if(mutation.type==='childList'){console.log(mutation);}});}letobserver=newMutationObserver(log);observer.observe(list,{childList:true});btnAdd.addEventListener('click',()=>{letitem=document.createElement('li');item.textContent='New Item';list.appendChild(item);console.log('Added new item');});btnRemove.addEventListener('click',()=>{if(list.lastElementChild){list.removeChild(list.lastElementChild);console.log('Removed last item');}});
Enter fullscreen modeExit fullscreen mode

Observing Child Element Changes

Observing Attribute Changes

JavaScript:

letdiv=document.querySelector('#myDiv');functionlogAttributes(mutations){mutations.forEach(mutation=>{if(mutation.type==='attributes'){console.log(mutation);}});}letobserver=newMutationObserver(logAttributes);observer.observe(div,{attributes:true});div.setAttribute('data-test','newValue');console.log('Updated data-test attribute');
Enter fullscreen modeExit fullscreen mode

Observing Subtree Changes

JavaScript:

letparent=document.querySelector('#parent');functionlogSubtreeChanges(mutations){mutations.forEach(mutation=>{if(mutation.type==='childList'&&mutation.addedNodes.length){console.log(mutation);}});}letobserver=newMutationObserver(logSubtreeChanges);observer.observe(parent,{childList:true,subtree:true});letchild=document.createElement('div');child.textContent='I am a new child!';parent.appendChild(child);console.log('Added a new child to the subtree');
Enter fullscreen modeExit fullscreen mode

Observing Character Data Changes

JavaScript:

lettextNode=document.querySelector('#textNode');functionlogCharacterDataChanges(mutations){mutations.forEach(mutation=>{if(mutation.type==='characterData'){console.log(mutation);}});}letobserver=newMutationObserver(logCharacterDataChanges);observer.observe(textNode,{characterData:true});textNode.textContent='New Text Content';console.log('Updated text content');
Enter fullscreen modeExit fullscreen mode

Accessing Old Values

JavaScript:

letdiv=document.querySelector('#myDiv');functionlogOldValues(mutations){mutations.forEach(mutation=>{if(mutation.type==='attributes'){console.log(`Old value:${mutation.oldValue}`);}});}letobserver=newMutationObserver(logOldValues);observer.observe(div,{attributes:true,attributeOldValue:true});div.setAttribute('class','newClass');console.log('Changed class attribute');
Enter fullscreen modeExit fullscreen mode

Conclusion

MutationObserver is a versatile and powerful tool for monitoring and responding to changes in the DOM. By understanding its constructor and methods, you can efficiently manage dynamic content and ensure your web applications are responsive to real-time updates.

Happy Coding!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

⚡I’m a curious coder who loves building things! Whether it’s creating beautiful website designs or making sure the behind-the-scenes stuff runs smoothly, I’m all in. Let’s turn code into magic! ⚡
  • Location
    Bihar- Bettiah
  • Education
    BE
  • Work
    Software Engineer at Qualminds
  • Joined

More fromDharmendra Kumar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp