Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

proper way to hide dynamic elements with jQuery

Tags:

jquery

hide

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();
});
like image 617
GrandVizier Avatar asked May 24 '10 19:05

GrandVizier


2 Answers

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.

like image 183
Nick Craver Avatar answered Oct 29 '22 20:10

Nick Craver


$("#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.
like image 39
user113716 Avatar answered Oct 29 '22 20:10

user113716