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();
});
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.
$("#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.
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