Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  132] [ 6]  / answers: 1 / hits: 184456  / 13 Years ago, thu, september 15, 2011, 12:00:00

I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I cannot modify its source. What are my options here?



I guess that, in theory, I could just use setInterval() to continually search for the element's presence and perform my action if the element is there, but I need a better approach.


More From » dom

 Answers
8

Warning!


This answer is now outdated. DOM Level 4 introduced MutationObserver, providing an effective replacement for the deprecated mutation events. See this answer to another question for a better solution than the one presented here. Seriously. Don't poll the DOM every 100 milliseconds; it will waste CPU power and your users will hate you.



Since mutation events were deprecated in 2012, and you have no control over the inserted elements because they are added by someone else's code, your only option is to continuously check for them.


function checkDOMChange()
{
// check for any new element being inserted here,
// or a particular node being modified

// call the function again after 100 milliseconds
setTimeout( checkDOMChange, 100 );
}

Once this function is called, it will run every 100 milliseconds, which is 1/10 (one tenth) of a second. Unless you need real-time element observation, it should be enough.


[#90082] Wednesday, September 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;