Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, why does setting outerHTML on an element set its parentNode to 'null'?

In Javascript, when I set the outerHTML of an element in the DOM to a new value (to change it into a different element, for example), its 'parentNode' property gets set to 'null'. Why? I would expect it to remain at whatever value it was at before the outerHTML change.

I guess that the DOM is creating a new object from parsing the 'outerHTML' string and using it to replace the original object. If this is the case, is there a method to retrieve that newly created object?

Steps to reproduce (tested on Linux Chrome & Linux Firefox)

  1. Open a clean window in your browser,

  2. Open the dev console (F12, probably)

  3. Take a look at the page DOM (Element tab in Chrome, Inspector in Firefox)

  4. Delete any children of the 'body', just to make things cleaner
  5. Open the console and type:

    obj1 = document.createElement('div')

    obj1.id = '1'

    document.body.appendChild(obj1);

    obj1.parentNode - Should write the 'body' HTML to the console.

    obj1.outerHTML = "<div id='2'></div>"

    obj1.parentNode - Now writes 'null' to the console.

like image 925
DrMcCleod Avatar asked Apr 14 '16 12:04

DrMcCleod


People also ask

Why is parentNode null?

Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.

What is outerHTML in Javascript?

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

What is the difference between innerHTML and outerHTML?

The outerHTML is the HTML of an element including the element itself. Use the outerHTML when you want to completely replace an element and its contents. Use innerHTML when you only want to replace the contents of the element.

Is there an outerHTML?

The outerHTML is the HTML of an element including the element itself. Contrast this with the innerHTML of the element, which is the HTML contained within an elements opening and closing tags. By definition, elements without both opening and closing tags do not have innerHTML.


1 Answers

This is as per doc

Also, while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element:

which means obj1 in your code is still referring to original element which has been detached from the DOM tree by now.

like image 71
gurvinder372 Avatar answered Sep 21 '22 16:09

gurvinder372