Why is a TR visible when not in DOM?
Why is a tr
element that hasn't been added to the DOM considered visible in jQuery, but a div
is not?
$('<tr></tr>').is(':visible') // returns true
$('<div></div>').is(':visible') // returns false
I'm using jQuery 1.4.2. I tested this in Firefox 5, IE 9, Chrome 12, and Safari 5, and Opera 11.5.
Resolution
I've written a workaround to use in my application until I can upgrade to a more recent version of jQuery:
$('<tr></tr>').is('body *:visible') // ret开发者_运维百科urns false
$('<div></div>').is('body *:visible') // returns false
Thanks for all the help everyone!
visible
doesn't mean that you can physically see it. It will still be true even when your eyes are closed, for example.
The node itself has no concept that the browser only renders one DOM tree.
It has no attributes set whereby an HTML browser would treat it as "invisible", therefore it is "visible"... even if it's not part of the one node tree that the browser's actually rendering.
You might also ask how $('<b>Bold text</b>')
can possibly be bold, or have any graphical formatting, when it cannot be seen.
From the documentation:
Elements can be considered hidden for several reasons:
- They have a CSS display value of none.
- They are form elements with type="hidden".
- Their width and height are explicitly set to 0.
- An ancestor element is hidden, so the element is not shown on the page.
Clearly none of these are true here.
I cannot explain why Dunhamzzz is able to produce a different result, though! It may be related somehow to the iframe
in which the fiddle runs.
Update
OK, jsfiddle.net has nothing to do with it.
However, I can reproduce this with 1.4.2.
So one or both of them is wrong. Given the inconsistent behaviour of tr
vs div
, I'd suggest that 1.4.2 is incorrect (there were a number of hidden-item-related changes in 1.4.4) and that the documentation is misleading.
Do a fiddle, both are false for me. Which is to be expected as they haven't been placed in the DOM yet and therefore have no styles/visibility applied to them.
精彩评论