Home > Software engineering >  How To Listen To HTML div class Text Changes and Fire Event If The Text Changes Using Javascript?
How To Listen To HTML div class Text Changes and Fire Event If The Text Changes Using Javascript?

Time:01-05

I am currently trying to listen the following HTML of a website, but don't really know how to go about it:

<dd >384455666</dd>

Everytime the site changes the numbers meaning in this case: "384455666", I want to fire an event. I know that an event listener for a button is following, but don't know how to do it in this case:

testing_button.addEventListener("click", reset);

CodePudding user response:

You can try this way with plain JavaScript and MutationObserver as someone metion before;

const targetElement = document.querySelector('.testingcode');

const observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log('Text content changed to:', mutation.target.textContent);
  });
});

observer.observe(targetElement, {
  characterData: true,
  childList: true,
  subtree: true
});

What this code does is creating a new MutationObserver and passes it a callback function that will be called every time the text content of the targetElement changes and then the callback function logs the new text content to the console.

You can modify the callback to do whatever you need.

Or you can use setInterval as well:

const targetElement = document.querySelector('.testingcode');

let previousTextContent = targetElement.textContent;

setInterval(function() {
  const currentTextContent = targetElement.textContent;
  if (currentTextContent !== previousTextContent) {
    console.log('Text content changed to:', currentTextContent);
    previousTextContent = currentTextContent;
  }
}, 1000);

It creates an interval that runs every 1 second. Inside the interval function, it gets the current text content of the targetElement and compares it to the previous value. If the values are different, it logs the new text content to the console and updates the previousTextContent variable.

  • Related