jQuery show method edge case

Neeraj Singh

By Neeraj Singh

on January 29, 2010

Here is a simple case of invoking show method on a hidden element.

1<style>
2  p {
3    display: inline;
4  }
5  #hello p {
6    display: none;
7  }
8</style>
9
10<div id="container">
11  <div id="hello">
12    Hello World
13    <p>this is p inside hello</p>
14  </div>
15</div>

jQuery code.

1$("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 .

1<style>
2  #container p {
3    display: inline;
4  }
5  #hello p {
6    display: none;
7  }
8</style>

See the result here . Notice that display property of p is block instead of inline .

Where did jQuery go wrong?

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.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.