<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:
p
is a parent container show all children
link, display
all child divs under p
lnkC1
or lnkC2
to hide
individual child divBut it seems that I didn't get .children()
working correctly. So how to fix it? Any ideas?
The :visible selector in jQuery is used to select every element which is currently visible. It works upon the visible elements. The elements that are consuming space in the document are considered visible elements. The height and width of visible elements are larger than 0.
jQuery :nth-child() Selector Selects all elements that are the nth-child of their parent. Syntax: $("Element:nth-child(Index/even/odd/equation)") Values: Index: Index provided. Index starts from.
The ("parent > child") selector selects all elements that are a direct child of the specified element.
children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With