Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect div change in javascript

I'm working on a small chrome extension for fun, and one thing I need it to be able to do, is to detect when the text inside a div is changed by the webpage itself.The code I'm using is:

var status = document.getElementById("status").innerHTML;
status.onchange = function() {
    console.log("CHANGE DETECTED")

And this doesn't seem to work, so what should I use instead?

NOTE: I'd prefer not to use jquery, as I am not even very proficient with javascript at the moment, but if it would be that much simpler/easier, that would be fine.

like image 509
Forceof Habit Avatar asked Oct 23 '25 14:10

Forceof Habit


2 Answers

use this trick

source:https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/

// select the target node
    var target = document.querySelector('#some-id');

    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            console.log(mutation.type);
        });
    });

    // configuration of the observer:
    var config = { attributes: true, childList: true, characterData: true }

    // pass in the target node, as well as the observer options
    observer.observe(target, config);

    // later, you can stop observing
    observer.disconnect();
like image 193
kishan Avatar answered Oct 26 '25 05:10

kishan


You can't do what you want using change event. On newer browsers, you can use Mutation Observers. On older browsers... well, you ask people to upgrade to newer browsers. :P

like image 33
Amadan Avatar answered Oct 26 '25 06:10

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!