6

DOMNodeInserted event is called when the node "be appended to", or "be appended"?

I ask this because the following code:

function AddTextToContainer () {
    var textNode = document.createTextNode ("My text");
    var container = document.getElementById ("container");

    if (container.addEventListener) {
        container.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
    }
    container.appendChild (textNode);
}

and that:

function AddTextToContainer () {
   var textNode = document.createTextNode ("My text");
   var container = document.getElementById ("container");

   if (textNode.addEventListener) {
       textNode.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
   }
   container.appendChild (textNode);
}

Both invoke OnNodeInserted in Chrome. Is it a bug?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lai Yu-Hsuan
  • 27,509
  • 28
  • 97
  • 164

2 Answers2

9

This is from W3C

DOMNodeInserted
Fired when a node has been added as a child of another node. 
This event is dispatched after the insertion has taken place. 
The target of this event is the node being inserted.
Bubbles: Yes
Cancelable: No
Context Info: relatedNode holds the parent node

The key is the Bubbles: Yes - thats why its being fired on the container as well.

Manse
  • 37,765
  • 10
  • 83
  • 108
-1

If you want to prevent the event from bubbling up just use event.stopPropagation(); in your text node callback. Events are then no longer handled up the dom tree.

ProTom
  • 1,194
  • 7
  • 7
  • `event.stopPropagation()` doesn't seem to have any effect for me. The event is still firing for children of the target. I have worked around it by checking that `event.target` is the object I think it is. – devios1 May 14 '12 at 21:41