ScG
ScG

Reputation: 1073

Selecting child element

I have the following div

       <div id="acc">
           <a href="#">Link 1</a>
           <div>
                Some Content
           </div>
           <a href="#">Link 2</a>
           <div>
               Some Content
           </div>
       </div>

All the div's are collapsed to start with. How can I select the first div child of 'acc' and say Slide Down on it

I have cached the selector like this:

var $acc = $(acc);

Upvotes: 0

Views: 133

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

Check out the first selector (or nth-child) and combine that with the children method:

$(acc).children('div:first').slideDown();

If you just want a single selector, then checkout the child selector:

$('#acc > div:first').slideDown();

how can I change it to slide up all div's except the first one.

Rather than try to find all-except, you may find it easier to mark the so-called "active" div:

$(acc).children('div:first').addClass('active').slideDown();

And find the previously marked div:

$(acc).find('.active').removeClass('active').slideUp();

However, if your goal is to create an accordion effect, you'll probably save yourself a lot of headaches by using a completed solution, such as jQuery UI's Accordion or any of numerous plugins.

Upvotes: 1

Jonathan
Jonathan

Reputation: 5993

Like this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                $("#acc").children().first().hide().slideDown('slow',function(){
                    // animation complete...
                });
            });

        </script>
    </head>
    <body>

        <div id="acc">
           <a href="#">Link 1</a>
           <div>
                Some Content
           </div>
           <a href="#">Link 2</a>
           <div>
               Some Content
           </div>
       </div>

    </body>
</html>

Upvotes: 0

Related Questions