I want to show first element that is hidden by jquery. my html code is:
<ol>
<li>1</li>
<li style="display:none">2</li>
<li style="display:none">3</li>
<li style="display:none">4</li>
<li style="display:none">5</li>
<li><a class="add">Add More ...</a></li>
</ol>
I want to show first hidden LI, each time that "a" element was clicked. My solution is below. but I think better way exists.
$("a.add").click(function(){
var hiddens=$(":hidden",$(this).parent().parent());
if (hiddens.length>0)
{
hiddens.each(function(index,el){
if(index==0)
{
$(this).slideToggle("fast");
}
});
}
if (hiddens.length==1)
{
$(this).parent().hide();
}
Tanx
To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element.
The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).
Definition and Usage. The :first-child selector selects all elements that are the first child of their parent. Tip: Use the :last-child selector to select elements that are the last child of their parent.
Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.
Just add a :first selector after you get :hidden set so you get the first element from set found by :hidden selector
$("a.add").click(function(){
$(":hidden:first").slideToggle("fast");
});
Here is the solution:
$("a.add").click(function(){
$(":hidden:first").show();
});
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