Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between DOMNodeInserted and DOMNodeInsertedIntoDocument?

According to the DOM events in wiki found in the wiki link here,

DOMNodeInserted: Fires when a node has been added as a child of another node

DOMNodeInsertedIntoDocument: Fires when a node is being inserted into a document

Now what is the real difference? Shouldn't both events be the same? If not when and where should be used?

The scenario where I am using the above mentioned DOM events is that, I have a set of pages and each page loads a nav.jsp file inside a div reserved for navigation. Now I want to highlight the current page's nav tab hence I give it a small background property after that DOM element ( nav DIV) is loaded.

Now for my problem:

$(document).on('DOMNodeInserted', function(e) { 
      if(e.target.id=="navigate"){
      //...........
      }
 });

worked, but just curious what is the difference is between the two events specified in my question?

like image 217
Sai Avatar asked Oct 27 '14 16:10

Sai


3 Answers

The DOMNodeInsertedIntoDocument event is similar to the DOMNodeInserted event, but it occurs when a node is inserted into the document.

For example, if a node is added to an element that is not a part of the document, the DOMNodeInserted event is fired but the DOMNodeInsertedIntoDocument event is not. If the parent element of a node is inserted into the document, the DOMNodeInsertedIntoDocument event is fired but the DOMNodeInserted event is not.

See JSFiddle: http://jsfiddle.net/ghyga4v6/2/

Try removing the container when text node is still there and inserting it back in to see the different events triggered.

like image 119
alchuang Avatar answered Oct 18 '22 01:10

alchuang


Here're two articles you can read about

  1. DOMNodeInsertedIntoDocument event
  2. DOMNodeInserted event

For example, you can insert Node into BOM element for developing browser extension or manipulate the history.

i.e. the BOM consists of the objects navigator , history , screen , location and document which are children of window . In the document node is the DOM, the document object model, which represents the contents of the page. You can manipulate it using javascript.(From wiki)

Here's a snippet to help, if you want to continue to learn.

$(window).on('DOMNodeInsertedIntoDocument', function(){
  console.log('DOMNodeInsertedIntoDocument occurred');
});

$(window).on('DOMNodeInserted', function(){
  console.log('DOMNodeInserted occurred');
});

By the way, just for your information. MutationObserver is replacing Mutation Events.

like image 41
Alan Dong Avatar answered Oct 18 '22 01:10

Alan Dong


They are not the same because the first one should also fire when adding a new node to a node that is outside of the document (created and not yet appended, or previously removed from its parent).

like image 1
user4011114 Avatar answered Oct 17 '22 23:10

user4011114