How to track text tag changes in jQuery

In jQuery, you can track changes to the text inside a <span> tag in several ways, depending on how the change happens. The main approach is to use MutationObserver, as it allows monitoring changes in the DOM. Here’s an example:

1. Using MutationObserver

$(document).ready(function () {
    const targetNode = document.querySelector('#mySpan'); // Your span element

    // Create the observer
    const observer = new MutationObserver((mutationsList) => {
        mutationsList.forEach((mutation) => {
            if (mutation.type === 'characterData' || mutation.type === 'childList') {
                console.log('Text changed:', mutation.target.textContent);
            }
        });
    });

    // Set up the observation
    observer.observe(targetNode, {
        characterData: true,  // Monitor text changes
        childList: true,      // Monitor addition/removal of child elements
        subtree: true         // Monitor the entire subtree within the tag
    });
});

2. Event via Custom Change

If the text is changed via jQuery or JavaScript (e.g., using .text() or .html()), you can manually trigger a custom event:

$(document).ready(function () {
    $('#mySpan').on('textChange', function () {
        console.log('Text changed to:', $(this).text());
    });

    // Example of changing the text
    $('#changeText').on('click', function () {
        $('#mySpan').text('New text').trigger('textChange');
    });
});

HTML:

<span id="mySpan">Old text</span>
<button id="changeText">Change Text</button>

If MutationObserver or custom events don’t suit you, you can use a timer to regularly check for changes:

$(document).ready(function () {
    let lastText = $('#mySpan').text();

    setInterval(() => {
        const currentText = $('#mySpan').text();
        if (currentText !== lastText) {
            console.log('Text changed:', currentText);
            lastText = currentText;
        }
    }, 500); // Check every 500ms
});

This method is less efficient but may be useful in specific situations.

Which method is better?

  • Use MutationObserver if the text is dynamically changed, and you need to monitor changes in the DOM.
  • Use the textChange event if the text changes are initiated by your own code.
  • The setInterval method is suitable for simple scenarios but less efficient.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more