Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find first element that is hidden by JQuery

Tags:

jquery

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

like image 295
Ata Avatar asked Dec 14 '08 10:12

Ata


People also ask

How do you check if an element is hidden using jQuery?

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.

How do you select the first element with the selector statement?

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).

Is first child jQuery?

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.

How do you check if HTML element is visible in jQuery?

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.


2 Answers

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");
});
like image 97
æther Avatar answered Sep 20 '22 13:09

æther


Here is the solution:

$("a.add").click(function(){
    $(":hidden:first").show();
});
like image 26
user38526 Avatar answered Sep 19 '22 13:09

user38526