I am trying to make a function go off when a particular div is created. In the simplest of terms, I have something like this:
<a href="" id="foo">Click me!</a>
<script>
$("#foo").live("click",function(e) {
e.preventDefault();
$(this).append($("<div />").html("new div").attr("id","bar"));
});
</script>
Before, I had mutation events listen for the creation of div#bar - something like this:
$("#bar").live("DOMNodeInserted", function(event) {
console.log("a new div has been appended to the page");
});
Is there an equivalent using Mutation Observers? I tried attrchange.js featured on Can you have a javascript hook trigger after a DOM element's style object changes? but that plugin only detects when an element has been modified, not when it's created.
This is code that listens for mutations on the childlist of
#fooand checks to see if a child with the id ofbaris added.However, this only observes
#foo. If you want to look for the addition of#baras a new child of other nodes, you need to observe those potential parents with additional calls toobs.observe(). To observe a node with the id ofbaz, you might do:The addition of the
subtreeoption means that the observer will look for the addition of#baras either a child or a deeper descendant (e.g. grandchild).