1

An external JavaScript adds a DOM element to a page.

Using JavaScript or JQuery how do I determine when this DOM element is added to the page?

4 Answers 4

1

You basically have three choices, one of which isn't available on all browsers:

  1. Get a notification from the other script that it's added an element (if it provides one)

  2. Poll (I'd use setTimeout and reschedule each following check on purpose) to see if the element appears. E.g.:

    var CHECK_INTERVAL = 100; 100 = 1/10th second, choose appropriate function checkForElement() { /* ...check for the element... */ if (/*...you found the element...*/) { // Do something with it } else { // Check again after a brief pause setTimeout(checkForElement, CHECK_INTERVAL); } } setTimeout(checkForElement, CHECK_INTERVAL); 
  3. Use a mutation observer, which is the replacement for the broken old mutation events. This lets you register a callback to be called on certain mutation events. Support is reasonable but — quelle shock — IE didn't get them until IE11.

Sign up to request clarification or add additional context in comments.

Comments

0

If you have access to that external javascript file, you can just call a function in your page from that file just after you add an element. If you don't have this facility or there is not event triggering in between, you can keep on checking existence of such element in a certain interval using javascript setInterval() method.

Comments

0
var chekElement = function (){ // this will rerun function every second var chekElemRecursiveTimer = setTimeout(chekElement, 1000); var someElement = $('.someElement'); if (someElement){ alert("its on page!"); clearTimeout(chekElemRecursiveTimer); } } // run function in page or from external js file chekElement(); 

Comments

0

another way to checked this

var chekForElement = function (){ var chekElementTimer = setTimeout(chekForElement, 1000); if ($('.chcekedElementclass').length > 0){ alert("found in page"); clearTimeout(chekElemRecursiveTimer); } } // run function in page or from external js file chekForElement(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.