ParentNode lost when javascript internally closes? Chrome error?

When I execute the following HTML test page in Chrome, I see the following in the debug console:

Has parent? true Has parent? false 

Do I really assume that this is a Chrome error (this does not happen in other browsers), or can Chrome rightfully do this for some reason? This led to an error in one of my web applications, and I finally highlighted this snippet to reproduce the main problem.

Here is the test page:

 <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body class=""> <script> function testDoodle() { var testParentEl = document.createElement('div'); var testChildEl = testParentEl.appendChild(document.createElement('div')); document.body.innerHTML+=('Has parent? ' + !!testChildEl.parentNode+'<br>'); console.log('Has parent? ' + !!testChildEl.parentNode); setTimeout(function() { document.body.innerHTML+=('Has parent? ' + !!testChildEl.parentNode+'<br>'); console.log('Has parent? ' + !!testChildEl.parentNode); }, 2000); return; } testDoodle(); </script> </body> </html> 

EDIT: I should have mentioned that I'm testing on Windows 7 with Chrome 49.0.2623.87 m (64-bit). It was also able to play OSX 10.11.2 with Chrome 49.

In addition, I must mention that sometimes it displays true / true, and sometimes true / false. You may need to reload the page several times to report a problem. I'm not sure, but it is possible that debugging tools (console) should also be open.

Thank you very much.

+6
source share
2 answers

I believe this is finally fixed by Chrome v50 (or at least I have not been able to play since the update).

0
source

I assume testChildEl.parentNode does not strongly refer to testParentEl , so it collects garbage.

Both testParentEl links inside the timeout and adding a strong testParentEl to testChildEl fix the problem for me:

 (function testDoodle() { var testParentEl = document.createElement('div'); var testChildEl = testParentEl.appendChild(document.createElement('div')); setTimeout(function() { testParentEl; // Prevents it from being garbage collected document.write('Has parent? ' + !!testChildEl.parentNode); }, 100); })(); 

 (function testDoodle() { var testParentEl = document.createElement('div'); var testChildEl = testParentEl.appendChild(document.createElement('div')); testChildEl.strongParent = testParentEl; // Prevents garbage collection setTimeout(function() { document.write('Has parent? ' + !!testChildEl.parentNode); }, 100); })(); 
0
source

All Articles