简体   繁体   中英

How to detect if inner text of div element changes and then record date / time of

I have the below which appears to be close, but still isn't printing in consol.log test . So, still not exactly. I want to continuously detect if my div element's content has changed (via inner text of elem) , record the inner text and date / time of change, and also the document referrer when this happens.

$(document).ready(function() {

var element = document.querySelector('.pet-name'); 

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName = 'data-pet-name') {

      var petname = $('.pet-name').text();
      var referrer = document.referrer;

      var date = new Date();
      var month = date.getUTCMonth() + 1;
      var day = date.getUTCDate();
      var year = date.getUTCFullYear();

      var time = date.toLocaleTimeString();
      var formattedDate = month + '/' + day + '/' + year;

            console.log(referrer); 
            console.log(petname); 
            console.log(time); 
            console.log(formattedDate); 
    }
  });
});

var config = { // some kind of attempt
  attributes: true,
  attributeFilter: ['pet-user-name']
};

observer.observe(element, config);

setTimeout(function() { // this is just for testing purposes of change elem
    $('.pet-name').text('Huge Fat Cat');
}, 6500);

});

Here's the FIDDLE . Cheerio.

What I see is that your if condition is never being met because you are not comparing, you are assigning. Without it, the code runs as expected. So, you need to correct that.

 $(function() { var element = document.querySelector('.pet-name'); // create an observer instance var observer = new MutationObserver(function(mutations) { var petname = $('.pet-name').text(); var referrer = document.referrer; var date = new Date(); var month = date.getUTCMonth() + 1; var day = date.getUTCDate(); var year = date.getUTCFullYear(); var time = date.toLocaleTimeString(); var formattedDate = month + '/' + day + '/' + year; console.log(referrer); console.log(petname); console.log(time); console.log(formattedDate); }); // 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(element, config); setTimeout(function() { $('.pet-name').text('Huge Fat Cat'); }, 1000); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="pet-name"> Big Fat Dog </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM