tags:

views:

110

answers:

3

I have a div element which my code will fill with a dynamic amount of links. Using jquery, I want to hide all the links except the first one. This is what I came up with and it works, I was just wondering if this is the best way to do it:

 
    $("#panelContainer").each(function(n) {
        $(this).children().hide();
        $("#panelContainer a:first").show();
    });
+8  A: 

You can shorten and speed it up it a bit using the :gt() (greater than) selector, like this:

$("#panelContainer :gt(0)").hide();

This assumes the children are all anchors, which seems to be the case from your question, use a:gt(0) if you need it to only affect links and there are other elements.

It's shorter because...well, it's shorter. It's faster because you're selecting the parent once, the children once and filtering, instead of parent, children, parent again and filtering descendants. Also, like your original, all links would be shown in the event javascript is disabled.

Nick Craver
+1, better than mine. Geez, there's always a slightly better way to do it than what I think!
Patrick Karcher
`$('#panelContainer a').slice(1).hide()` would be fastest, fwiw. Anytime you can use a method instead of relying on sizzle you get a speed boost.
Paul Irish
+4  A: 
$("#panelContainer a:not(:first-child)").hide();

Since the a elements are added dynamically, it may be beneficial to add them as hidden elements, then show the first (if it works with the intention of your application).

The following assumes the initial state is hidden.

$("#panelContainer a:first-child").show();  // Instead of hiding many, 
                                            //    you could show one.
patrick dw
+2  A: 

There are just a few CSS only alternatives with examples here. Read up about compatibility of selectors at quirksmode. Could be used as selectors in jQuery as well with the hide() function.

Starting with n+2 or the second child

#panelContainer :nth-child(n+2) {
    display: none;
}

All anchors that come after the first child anchor

#panelContainer > a + a {
    display:none;
}​

@patrick, All child nodes except the first one

#panelContainer > :not(:first-child) {
    display: none;
}
​

Thanks again to @patrick for suggesting this super cross-browser method. First hide all links, then show the first one

#panelContainer > a {
    display: none;
}

#panelContainer > a:first-child {
    display: inline;
}
Anurag
+1 - Makes sense to do a CSS approach. Another browser compatible version would be #panelContainer a { display: none;}#panelContainer a:first-child { display: inline;}
patrick dw
That seems to be the most cross-browser way to be honest even more than `* > a + a`.
Anurag