Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery show() vs adding Class

Which of these is more efficient (i.e. faster):

$(elem).show();

or

$(elem).addClass(displayClass); // Where display class is "display: block;"

Or are they identical?

like image 382
bba Avatar asked Nov 10 '10 13:11

bba


People also ask

What does show () do in jQuery?

jQuery Effect show() Method The show() method shows the hidden, selected elements. Note: show() works on elements hidden with jQuery methods and display:none in CSS (but not visibility:hidden).

What is add class in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Has class add and remove jQuery?

jQuery Manipulating CSSaddClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.

Can you add multiple classes to an element jQuery?

Approach: First select the element to which multiple classes will be added. Then use addClass() method to add multiple classes to the element and removeClass() method to remove multiple classes.


2 Answers

It depends what you're after, they do different things:

  • $(elem).show(); - shows the element, restoring the display from before .hide() or restoring the default display for the element type
  • $(elem).addClass(displayClass); - adds a class, always with a certain display, not really restoring what was there - this is less flexible

Which is faster? .addClass() hands down, you can test it yourself here, it simply does a lot less work than .show() does. However, it doesn't do as much feature-wise, so it's less flexible for the reasons above.

like image 56
Nick Craver Avatar answered Sep 18 '22 14:09

Nick Craver


No, they are absolutely not identical.

There's a big difference between direct modifications to element styles and "indirect" modifications by changing the element's class, and that really should be pretty obvious. By writing cooperative code between Javascript and CSS, the class changes give you a lot more flexibility. The Javascript manages the state of elements, while the CSS drives the actual effect of that state.

The show() and hide() methods are handy and easy, but (in my opinion) managing state/appearance by class name is really a much more powerful and maintainable way to do things. In fact you can always write your own little jQuery plugins to add/remove classes that are meaningful to your app, to avoid having the class names themselves propagate through your code.

like image 34
Pointy Avatar answered Sep 20 '22 14:09

Pointy