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?
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).
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.
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.
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.
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 flexibleWhich 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.
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.
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