Ways to identify a modification in a div or body element?

I need help detecting changes in the content and body elements using JavaScript. The logic cannot be applied directly to the button itself.

Are there any events available for this purpose? Can you provide a code sample?

Check out this JS Bin link for reference.

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <script>
        window.App = {
            start: function () {
                var btn = document.getElementById('addContent');
                btn.addEventListener('click', function () {
                    var body = document.getElementsByTagName('body')[0];
                    body.innerHTML += '<p>ADDED LATER - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>';
                });

                //---
                // does not work i need the content
                window.addEventListener('resize', function () {
                    console.log('content / window / resize');
                });

                var content = document.getElementById('content');
                content.addEventListener('change', function () {
                    console.log('content / div / resize');
                }.bind(this));
            }
        };
    </script>
</head>


<body onload="App.start();">
    <div id="content">
        <button id="addContent" type="button">Add content!</button>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    </div>
</body>

</html>

Answer №1

MutationObserver allows developers to respond to any changes in the DOM.

To learn more, visit MDN or MSDN

You can also check out this discussion thread: here

Answer №2

Here's a unique idea that might not fully meet your needs: You could establish a custom event and activate it at any point:

window.App = {
    start: function () {
        var customEvent = new Event("customEvent"), // your custom event
            content = document.getElementById('content'),
            btn = document.getElementById('addContent');
        
        btn.addEventListener('click', function () {
            var body = document.getElementsByTagName('body')[0];
            body.innerHTML += '<p>ADDED LATER - Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>';

            // activate it
            content.dispatchEvent(customEvent);
        });
        
        content.addEventListener('customEvent', function () {
            console.log('content / div / resize');
        });
    }
};
App.start();
<div id="content">
    <button id="addContent" type="button">Add content!</button>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

Answer №3

Take a look at this resource

Instead of 'change', consider using 'DOMNodeInserted' and updating the HTML of a div with ID content instead of the innerHTML of body

You can also check for content / div / resize messages in your browser console

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

Converting keyValue format into an Array in Angular using Typescript

Is there a way to change the key-value pair format into an array? I have received data in the following format and need to convert it into an array within a .TS file. countryNew: { IN: 159201 BD: 82500 PK: 14237 UA: 486 RU: 9825 } This needs to be transf ...

Spacing for Bootstrap Navbar List Items

I've searched through the CSS and I'm unable to identify what is causing the width between the top level links on my navbar. I need them to be slightly smaller so that when it adjusts for a screen below 900px, it doesn't convert into a 2-row ...

What is the best class to implement in my jQuery code?

Currently in the process of developing a customized Google Chrome extension. Encountering an issue or experiencing confusion regarding the selection of a specific class to integrate into my jQuery script, particularly with numerous classes associated with ...

Showing scheduled activities from a database on an AngularJS mwl calendar

How can I modify my code to display events from a database on an mwl calendar based on the saved date rather than showing all events for today only? I want to show events based on the notifyDate field in the database. Can someone help me with this? html ...

Parent Route Abstractions in Vue-Router

I am currently in the process of transitioning my existing website to vuejs. The navigation structure I aim for is as follows: /login /signup /password-reset /browse /search ... numerous other paths Since some of these paths have similar functionalities, ...

Scrape tags from the web using Python's Selenium for a unique collection

Hello there! I appreciate you taking the time to read through this. I'm currently navigating my way through Python and Selenium, specifically attempting to crawl web pages like this one and others of a similar nature. One challenge I've come acro ...

Utilizing multiple forms in AngularJS

As I delve into the world of AngularJS, I've managed to create a news page where users can comment on articles. However, I'm not entirely satisfied with the way I use classic JavaScript to dynamically fetch story forms. Is there a cleaner approac ...

Monitoring $scope modifications within a directive: A simple guide

I am currently working with a directive that looks like this: app.directive('selectedForm', function(MainService) { return { scope: { formName: '=currentForm' }, restrict: 'E', ...

What is the best way to choose all text within a code box without highlighting the entire webpage?

I developed a CSS code specifically for my blogspot site to organize and store all of my code and technical snippets. .code { background:#dae6ef; background-repeat:no-repeat; border: solid #5C7B90; border-width: 1px 1px 1px 20px; color ...

Stop javascript function from automatically invoking itself

I am new to php and javascript and currently working on using a session variable to keep track of a counter. I want the counter to increment on the next button click and decrement on the previous button click. The issue I'm facing is with the JavaScri ...

Tips for Adding For Loop Value to an Array in JavaScript

Trying to Add For Loop Value to an Array My Current View <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <style> body { font-family: Roboto, sans-serif; } #chart { max-width: 650px; margin: 35px auto; ...

On smaller screens in portrait mode, CSS automatically incorporates margin adjustments

Here is the code I am working with: <html> <head> <style> body { margin: auto; width: 720px; } </style> </head> <body> <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ip ...

Efficiently Encoding Still Image Data for NextJS

Currently, I am experimenting with a completely static method in my new Next.js v12 project. I am creating 5-6 data files to use with getStaticProps. Here is an example of one of the data file structures (they are all similar): import SqAshland1 from &apos ...

Problem with Jquery HTML CSS Slideshow

Currently I am working on integrating two sliders into one webpage using the demo available at . One of the sliders is customized from the Linking demo and I have named them slider1 and slider2 with different styling using global.css for slider-1 and text. ...

Shift the items in the unordered list to the left

I am currently working on a carousel design. I have already finished coding the HTML and CSS, but I am unsure of how to shift the elements one by one to the right or left while ensuring that 7 pictures are always visible in the viewport. .seccion { ...

How to determine if a div is within the viewport with jQuery

I am attempting to utilize jQuery to determine if Div RED is currently visible within the viewport, and if not, then check for the visibility of Div ORANGE. The function I have implemented works perfectly when there is only one IF statement, but as soon as ...

Can you explain the contrast between uploading files with FileReader versus FormData?

When it comes to uploading files using Ajax (XHR2), there are two different approaches available. The first method involves reading the file content as an array buffer or a binary string and then streaming it using the XHR send method, like demonstrated he ...

Initiate gapi.auth2 upon VueJs initialization

I am currently developing a Vue.js web application that allows users to connect with their Google accounts. The login process, both front-end and back-end, is functioning properly: the Google sign-in button is displayed, the user clicks on it, and their a ...

Discover properties of a TypeScript class with an existing object

I am currently working on a project where I need to extract all the properties of a class from an object that is created as an instance of this class. My goal is to create a versatile admin page that can be used for any entity that is associated with it. ...

What is the method to trigger the jQuery 'mouseenter' event on an element using Selenium?

Struggling to automate a scenario using selenium where I need to click on a menu element. I've tried various methods, except jQuery. WebDriver normal click and JavaScript click() haven't worked. Can someone assist me with implementing jQuery in s ...