proper way to hide dynamic elements with jQuery
I have a div element which my code will fill with a dynamic amount 开发者_Python百科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.
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;
}
精彩评论