0

Is there a DOM event that fires when elements are created?

I'm using the script below to scan for and remove a HTML div that is created dynamically.

I'd prefer to hook into the DOM event model instead of polling.

function remove_new_element(){
    document.getElementsByClassName("new_element")[0].remove();
    clearInterval(lookfor_new_element);  
}

function lookfor_new_element(){     
  (document.getElementsByClassName("new_element").length==1)?
  remove_new_element():null;     
}

setInterval(lookfor_new_element,1000)
John Montgomery
  • 6,739
  • 9
  • 52
  • 68
Kickaha
  • 3,680
  • 6
  • 38
  • 57
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver – epascarello Apr 24 '19 at 14:15
  • 3
    Don't do this - call your function when the function that removes the element gets called, don't listen for changes in the DOM. – Adam Jenkins Apr 24 '19 at 14:16
  • You would be better off firing some event when the page changes than listening/checking for something. So if you can alter the code to fire a custom event, do it. – epascarello Apr 24 '19 at 14:16
  • I must intervene - the dupe answers the question you asked, but, as is often the case on SO, it doesn't answer the question that you really wanted to know the answer to. Using your DOM as a "source of truth" - whatever is or isn't in the DOM should be based on your application's state, not the other way around - is a really bad idea. – Adam Jenkins Apr 24 '19 at 14:18
  • @Adam this is a greasemonkey script. It's not my page, the mutationObserver looks to be the answer I was looking for. – Kickaha Apr 24 '19 at 14:20
  • 1
    @Kickaha - phew. I missed the tag on the question. You're all good! – Adam Jenkins Apr 24 '19 at 14:22
  • @Adam this has the `greasemonkey-4` tag, so I assume that it's about a userscript. How would you hook a *user* function to an existing application? We are talking about a generic way. – VLAZ Apr 24 '19 at 14:23

0 Answers0