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
You can use livequery plugin for jQuery. You can provide a selector expression such as:
$("input[type=button].removeItemButton").livequery(function () {
$("#statusBar").text('You may now remove items.');
});
Every time a button of a removeItemButton
class is added a message appears in a status bar.
In terms of efficiency you might want avoid this, but in any case you could leverage the plugin instead of creating your own event handlers.
Revisited answer
The answer above was only meant to detect that an item has been added to the DOM through the plugin.
However, most likely, a jQuery.on()
approach would be more appropriate, for example:
$("#myParentContainer").on('click', '.removeItemButton', function(){
alert($(this).text() + ' has been removed');
});
If you have dynamic content that should respond to clicks for example, it's best to bind events to a parent container using jQuery.on
.