learn.jquery.com icon indicating copy to clipboard operation
learn.jquery.com copied to clipboard

Explain how to test if element attached to main DOM

Open Enelar opened this issue 8 years ago • 5 comments

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.

Enelar avatar Sep 03 '16 09:09 Enelar

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.

jquerybot avatar Sep 03 '16 09:09 jquerybot

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.

AurelioDeRosa avatar Sep 06 '16 16:09 AurelioDeRosa

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 avatar Sep 06 '16 16:09 AurelioDeRosa

@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

Enelar avatar Sep 07 '16 11:09 Enelar

Hi @Enelar. I'm OK with your example too as far as we have one to clarify the concept.

AurelioDeRosa avatar Sep 11 '16 23:09 AurelioDeRosa