74
document.getElementById("elementId").style.display="none"

is used in JavaScript to hide an element. But in jQuery,

$("#elementId").hide();

is used for the same purpose. Which way is more efficient? I have seen a comparison between two jQuery function .hide() and .css("display","none") here.

But my problem is whether pure JavaScript is more efficient than jQuery?

Community
  • 1
  • 1
Maninda
  • 1,896
  • 3
  • 13
  • 28
  • Possible duplicate of [.hide() or display: none? jQuery](http://stackoverflow.com/questions/4396983/hide-or-display-none-jquery) – Somnath Muluk Aug 22 '16 at 11:28

4 Answers4

126

Talking about efficiency:

document.getElementById( 'elemtId' ).style.display = 'none';

What jQuery does with its .show() and .hide() methods is, that it remembers the last state of an element. That can come in handy sometimes, but since you asked about efficiency that doesn't matter here.

jAndy
  • 212,463
  • 51
  • 293
  • 348
  • 2
    Yes this is more efficient but this isn't safe. In my job there is a HUGE web application which is pretty much entirely configurable, so depending on the context and configuration some items might or might not be in the page. If this element isn't present in the page, this WILL cause an error (using .style on an undefined object). With JQuery you won't have that problem, or if not you should check `if( document.getElementById( 'elemtId' ) )` before doing it. – dominicbri7 Oct 23 '15 at 13:45
28
a = 2;

vs

a(2);
function a(nb) {
    lot;
    of = cross;
    browser();
    return handling(nb);
}

In your opinion, what do you think is going to be the fastest?

Florian Margaine
  • 50,873
  • 14
  • 87
  • 110
26

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Jamund Ferguson
  • 15,537
  • 3
  • 40
  • 49
  • 2
    I wouldn't say that. Depending on the number of calls, this *can become a factor*, since we're calling the jQuery constructor method each time. – jAndy Dec 03 '12 at 17:13
  • 1
    If you're doing this > 10,000 times in a second it may become noticeable. I can prove it :) – Jamund Ferguson Dec 03 '12 at 17:14
  • Love the link to jsperf.com/jquery-hide-vs-native33. Thank you! – Ace Feb 08 '13 at 18:22
6

Yes.

Yes it is.

Vanilla JS is always more efficient.

Naftali aka Neal
  • 138,754
  • 36
  • 231
  • 295