admin管理员组

文章数量:1304878

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?

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?

Share Improve this question edited Oct 18, 2019 at 16:41 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 26, 2011 at 9:30 Lai Yu-HsuanLai Yu-Hsuan 28.1k29 gold badges99 silver badges168 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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.

本文标签: javascriptWhen is quotDOMNodeInsertedquot event calledStack Overflow