1

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.

Xiaolin Wu
  • 179
  • 1
  • 3
  • 13
  • What is `"starts to exist"`? – void Mar 02 '18 at 13:12
  • By "starts to exist" I assume you mean "added to the DOM"? Code based on setInterval ought to let you discover it, but obviously it's not very efficient. What causes this element to be created? Presumably it's some other JS code? Is it your code? You could make that code emit an event to say that it's added the element, and then listen for that – ADyson Mar 02 '18 at 13:12
  • Elements don't pop into existence spontaneously. If it was not there before and gets added to the DOM, then it means that some script added it. So you don't need to detect when it is added, since _you_ add it. – Jeremy Thille Mar 02 '18 at 13:12
  • If you're OK with using jQuery, this thread has an easy solution https://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements – Mihalis Bagos Mar 02 '18 at 13:13
  • Turns out this feature, mutation events is now being dropped completely. https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events#Browser_compatibility, you can use MutationObserver instead: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – Mihalis Bagos Mar 02 '18 at 13:16
  • Yes, I mean "added to the DOM" but the .parent is written in html code and I want to create some other elements inside the .parent with raw js – Xiaolin Wu Mar 02 '18 at 13:17
  • 1
    So, since it's written in the HTML code, it's already here. Why would you need to detect when it appears?? – Jeremy Thille Mar 02 '18 at 13:18
  • OK thanks for the suggestions! – Xiaolin Wu Mar 02 '18 at 13:19
  • @JeremyThille I want to put js code in the head of the page – Xiaolin Wu Mar 02 '18 at 13:20
  • 1
    So then if this element already exists, do you really just want to run some code when the page loads? – ADyson Mar 02 '18 at 13:20

3 Answers3

4

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

Mihalis Bagos
  • 2,500
  • 1
  • 22
  • 32
  • Since only elements that exist can be observed this can return an error, but this can be fixed just adding for example: observer.observe(target || document, config); – Bruno de Oliveira May 30 '22 at 04:22
2

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>
mshouman
  • 374
  • 2
  • 12
0

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>
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129