January 29, 2010
Here is a simple case of invoking show
method on a hidden element.
<style>
p {
display: inline;
}
#hello p {
display: none;
}
</style>
<div id="container">
<div id="hello">
Hello World
<p>this is p inside hello</p>
</div>
</div>
jQuery code.
$("p").show();
You can see the result here . Notice that when p
is shown then display
property of p
is inline
which is what it should be.
All is well.
Now I'll change the css a little bit and will try the same code again. New css is .
<style>
#container p {
display: inline;
}
#hello p {
display: none;
}
</style>
See the result here . Notice that display
property of p
is block
instead of inline
.
jQuery did not do anything wrong. It is just being a bit lazy. I'll explain.
Since the element was hidden when jQuery was asked to display it, jQuery had no
idea where the element should have display property inline
or block
. So
jQuery attempts to find out the display property of the element by asking
browser what the display property should be.
jQuery first finds out the nodeName of the element. In this case value would be
P
. Then jQuery adds a P
to body and then asks browser what is the display
property of this newly added element. Whatever is the return value jQuery
applies that value to the element that was asked to be shown.
In the first experiment, css style p { display: inline; }
said that all p
elements are inline. So when jQuery added a new p element to body and asked
browser for the display property, browser replied 'inline' and 'inline' was
applied to the element. All was good.
In the second case, I changed the stylesheet #container p { display: inline; }
to have only p elements under id hello
to have inline property. So when jQuery
added a p element to body and asked for display type, browser correctly replied
as 'block'.
So what's the fix.
Find the parent element (#hello) of the element in question ( p in this case) . jQuery should add a new p element to the #hello and then jQuery would get the right display property.
If this blog was helpful, check out our full blog archive.