bob
bob

Reputation: 197

Does specific element exist event

Is there any event to know when a specific element "starts to exist" in raw javascript? For example I have

<div class="parent">
  <div class="child"></div>
</div>

And I want to do something when .parent and only the .parent (not the .child) "starts to exist" using an event instead of putting js code inside of it. I tried to setInterval and check whether the .parent exists.

Upvotes: 1

Views: 4059

Answers (3)

Okan Kocyigit
Okan Kocyigit

Reputation: 13441

You can handle DOM Changes with DOMSubtreeModified.

With jQuery

$(function() {
  $(".parent-wrapper").bind("DOMSubtreeModified", function() {
     if ($(this).find(".parent")) {
        alert("hey a new element with 'parent' class seems to be exist")
     }
  });
  
  
  //lets simulate dom change
  setTimeout(function() {
      $(".parent-wrapper").append('<div class="parent"><div class="child">test</div></div>');
   }, 3000);
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="parent-wrapper">
  
</div>

Update:

Here is the pure javascript version,

document.getElementById("parent-wrapper").addEventListener('DOMSubtreeModified', function () {
  alert("hey a new element with 'parent' id seems to be exist")
}, false);

//lets simulate dom change
  setTimeout(function() {
      document.getElementById("parent-wrapper").innerHTML = '<div class="parent"><div class="child">test</div></div>';
   }, 3000);
<div id="parent-wrapper">
  
</div>

Upvotes: 0

Mihalis Bagos
Mihalis Bagos

Reputation: 2510

This feature, mutation events using DOMSubtreeModified etc, is now being dropped completely. as shown here, but you can use MutationObserver instead specs here

A simple example on how to use it taken from here this:

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        console.log(mutation.type);
    });
});

// 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(target, config);

// later, you can stop observing
observer.disconnect();

You can get all the configuration parameters for the observer config object here MutationObserverInit

Upvotes: 4

mshouman
mshouman

Reputation: 384

I can't imagine what you want to do but I hope this will help you

<div class="parent" onload="yourFunction()">
     <script>
         function yourFunction(){
             // your code
         }
     </script>
     <div class="child"></div>
</div>

Upvotes: 2

Related Questions