How can I detect or trigger an event when text in <p> tag is changed?

I want to trigger an event when text inside a <p> tag has changed. I thought to use change() but I realize it’s meant for form input elements.

<script src=""></script>
  <p> Hello </p>
<button id="click">click to change</button>
$("#click").click(function() {

What triggers the <p> text to change? Maybe put the event you want in those other triggers?

take a look at this post and see if it can solve your issue.

You could use the MutationObserver interface.

Example (modified from the MDN):


  <p>This paragraph is not being watched.</p>
  <p id="watch">This paragraph is being watched.</p>

<button id="change-text">Change watch paragraph text</button>
<button id="add-span">Add span element to watch paragraph</button>


// Select the node that will be observed for mutations
var targetNode = document.getElementById('watch');

// Options for the observer (which mutations to observe)
var config = { childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('watch paragraph has changed or child has been added/removed');

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

document.getElementById('change-text').addEventListener('click', function(){
  targetNode.textContent = 'new text';

document.getElementById('add-span').addEventListener('click', function(){
  var node = document.createElement('SPAN');                 // Create a <li> node
  var textnode = document.createTextNode('My Span');         // Create a text node
  node.appendChild(textnode);                              // Append the text to <li>
1 Like