learn.jquery.com
learn.jquery.com copied to clipboard
Explain how to test if element attached to main DOM
When appending DOM elements to a DocumentFragment, browsers detach them from the page. So, if you access the value of the .length property of a previously stored variable containing those elements, its value will not change, even if the elements have been detached.
Since DocumentFragment era .length
do not provide accurate answer to that question in several scenarios.
Thank you for your pull request. It looks like this may be your first contribution to a jQuery Foundation project, if so we need you to sign our Contributor License Agreement (CLA).
:memo: Please visit http://contribute.jquery.org/CLA/ to sign.
After you signed, the PR is checked again automatically after a minute. If there's still an issue, please reply here to let us know.
If you've already signed our CLA, it's possible your git author information doesn't match your CLA signature (both your name and email have to match), for more information, check the status of your CLA check.
Thank you for the PR, you made a good point. I have a few suggestions to improve it.
I'd move this paragraph as the first of your PR to explain the potential issue:
When appending DOM elements to a DocumentFragment, browsers detach them from the page. So, if you access the value of the
.length
property of a previously stored variable containing those elements, its value will not change, even if the elements have been detached.
I was thinking that it might worth to show an example.
An example of such behavior is illustrated below:
var span = $( "span" );
var fragment = document.createDocumentFragment();
console.log( span.length ); // 1
fragment.appendChild( span.get( 0 ) );
console.log( span.length ); // Still 1!
console.log( $( "span" ).length ); // 0. The element was detached
Any thoughts?
@AurelioDeRosa it may confuse if you don't use DocumentFragment
directly.
(Google Chrome 54)
$('body').html('<div><a></a></div>');
var element = $('body a');
console.log(element.length); // 1
console.log(element.parents().length); // 3 div, body, html
$('body').html('');
console.log(element.length); // 1
console.log(element.parents().length); // 1 div
Hi @Enelar. I'm OK with your example too as far as we have one to clarify the concept.