Search code examples
jquery

Trigger event when an element exists


I have an empty div element:

<div class="message"></div>

At certain point of the webpage, a p tag is dynamically added to the div:

<div class="message">
  <p>Some Message</p>
</div>

The p can get removed, then added again and so.

What event should I use to listen if the div.message has a p child and execute some code?

I found this question, but it involves external plugins.

Isn't there an easy way to accomplish this?


Solution

  • Depending on your implementation and how fast you need to recognize a change, you might be able to get away with using a setInterval to periodically monitor the contents of a certain element.

    var checkContents = setInterval(function(){
      if ($("div.message p").length > 0){ // Check if element has been found
        // There is a <p> element in here!!
        console.log($("div.message p").length());
      }
    },1000);
    

    The previous snippet will check for <p> elements within div.message elements every second (1000 milliseconds), and if present will log the number of them to the console.


    Depending on your browser support requirements, you could alternatively use mutation events -

    Mutation events provide a mechanism for a web page or an extension to get notified about changes made to the DOM...

    var element = document.querySelectorAll('div.message')
    element.addEventListener("DOMNodeInserted", function (ev) {
      // ...
    }, false);