Kevin Burke Kevin Burke - 1 year ago 74
jQuery Question

Event when element added to page

This was previously discussed here: How to do an action when an element is added to a page using Jquery?

The responder suggested triggering a custom event whenever a div was added to the page. However, I'm writing a Chrome extension and don't have access to the page source. What are my options here? I guess in theory I could just use

to continually search for the element's presence and add my action if the element is there.

Answer Source

Since DOM Mutation Events are now deprecated (see note at the bottom) with the latest specifications, 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 xxx milliseconds. I choose 100, which is 10 times a second. Unless you need real time elements catch, it should be enough.


As commented by Ben Davis, DOM Level 4 specification introduces Mutation observers (also on Mozilla docs), which replace the deprecated mutation events.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download