6
<a href="javascript:(void);" id="lnkP">show all children</a>
<a href="javascript:(void);" id="lnkC1">hide child 1</a>
<a href="javascript:(void);" id="lnkC2">hide child 2</a>

<div id="p" style="display:none;">
<div id="c1">child 1</div>
<div id="c2">child 1</div>...
</div>​

$("#lnkP").click(function(){
    $("#p").children().show(); //seems there's a problem here...
});
$("#lnkC1").click(function(){
   $("#c1").hide(); 
});
$("#lnkC2").click(function(){
   $("#c2").hide(); 
});​

jsFiddle: http://jsfiddle.net/CBGsF/1/

What I am trying to do is:

  1. p is a parent container
  2. click show all children link, display all child divs under p
  3. click lnkC1 or lnkC2 to hide individual child div

But it seems that I didn't get .children() working correctly. So how to fix it? Any ideas?

halfer
  • 19,824
  • 17
  • 99
  • 186
woodykiddy
  • 6,074
  • 16
  • 59
  • 100
  • As jQuery selector is basically CSS selectors with some additional custom things, so would this work? http://stackoverflow.com/questions/4910077/select-all-child-elements – Alvin Wong Dec 07 '12 at 04:57

5 Answers5

8

Since the parent (#p in your case) has a display:none, it's children won't be visible.

You'll need to show the parent first,

$("#p")
.show()
.children().show();

(jQuery's chaining, very helpful)

Please try and get rid of the inline styling (it gets unmanageable after a while), use classes as much as possible.

You can have a class in css,

.displayNone
{
    display: none;
} 
.displayBlock
{
   display: block;
}

And then use jquery methods .removeClass(), .addClass() or .toggleClass() to show/hide your elements.

This is just a recommendation :)

Test link: http://jsfiddle.net/CBGsF/8/

painotpi
  • 6,894
  • 1
  • 37
  • 70
2

You need to show the #p also

Updated fiddle: http://jsfiddle.net/CBGsF/7/

$("#lnkP").click(function(){
    $("#p").show().children().show(); //Add show() before children.show call
});
$("#lnkC1").click(function(){
   $("#c1").hide(); 
});
$("#lnkC2").click(function(){
   $("#c2").hide(); 
});​
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
1

Updated fiddle : http://jsfiddle.net/CBGsF/5/

$("#lnkP").click(function(){
$("#p").show();
$("#p").children().show();
});
  $("#lnkC1").click(function(){
   $("#c1").hide(); 
});
$("#lnkC2").click(function(){
   $("#c2").hide(); 
});​
Anujith
  • 9,370
  • 6
  • 33
  • 48
1

Parent element is set to "display":"None" That is the problem

$("#p").css("display","block"); //is required in show all anchor click

Check the fiddle

http://jsfiddle.net/CBGsF/6/

Thanks

Sridhar Narasimhan
  • 2,643
  • 2
  • 17
  • 25
0

(Posted solution on behalf of the question author).

I thought .children() would search for invisible nodes as well. Well, I was wrong on that.

halfer
  • 19,824
  • 17
  • 99
  • 186