admin管理员组文章数量:1293068
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)
Open a clean window in your browser,
Open the dev console (F12, probably)
Take a look at the page DOM (Element tab in Chrome, Inspector in Firefox)
- Delete any children of the 'body', just to make things cleaner
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.
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)
Open a clean window in your browser,
Open the dev console (F12, probably)
Take a look at the page DOM (Element tab in Chrome, Inspector in Firefox)
- Delete any children of the 'body', just to make things cleaner
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.
- Related: stackoverflow./q/31550944/1461424 – sampathsris Commented Apr 4, 2017 at 7:31
1 Answer
Reset to default 7This 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.
本文标签:
版权声明:本文标题:html - In Javascript, why does setting outerHTML on an element set its parentNode to 'null'? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741570930a2386004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论