250

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you to write less and do ... well the same amount. And may also yield performance benefits.

A specific example

$(this) vs this

Inside a click event referencing the clicked objects id

jQuery

$(this).attr("id");

Javascript

this.id;

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

EDIT : While I appreciate the answers regarding jQuery vs. plain javascript performance, I am actually looking for much more quantitative answers. While using jQuery, instances where one would actually be better off (readability/compactness) to use plain javascript instead of using $(). In addition to the example I gave in my original question.

j08691
  • 204,283
  • 31
  • 260
  • 272
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
  • I'm not sure I understand the question. Were you looking for opinions on the merits of using library code, or were you looking for additional non-jQuery cross-browser compatible techniques akin to `this.id`? – user113716 Jan 10 '11 at 22:41
  • 1
    from the answers it seems like everyone is taking this question as philosophical, as I intended it to be very quantitative, as to almost compile a list of instances like the one I outlined that are common (mal)practices. – jondavidjohn Jan 10 '11 at 22:44
  • 78
    relevant http://www.doxdesk.com/img/updates/20091116-so-large.gif – goat Jan 11 '11 at 01:46
  • 5
    @chris also http://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492 – Tyler Jan 11 '11 at 05:31

13 Answers13

211
  • this.id (as you know)
  • this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
  • this.className to get or set an entire "class" property
  • this.selectedIndex against a <select> to get the selected index
  • this.options against a <select> to get a list of <option> elements
  • this.text against an <option> to get its text content
  • this.rows against a <table> to get a collection of <tr> elements
  • this.cells against a <tr> to get its cells (td & th)
  • this.parentNode to get a direct parent
  • this.checked to get the checked state of a checkbox Thanks @Tim Down
  • this.selected to get the selected state of an option Thanks @Tim Down
  • this.disabled to get the disabled state of an input Thanks @Tim Down
  • this.readOnly to get the readOnly state of an input Thanks @Tim Down
  • this.href against an <a> element to get its href
  • this.hostname against an <a> element to get the domain of its href
  • this.pathname against an <a> element to get the path of its href
  • this.search against an <a> element to get the querystring of its href
  • this.src against an element where it is valid to have a src

...I think you get the idea.

There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.

In general you can replace:

$(el).attr('someName');

with:

Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.

The sentences below sort of covered it. See this answer for a better treatment.

el.getAttribute('someName');

...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.

Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:

$('span').unwrap();  // unwrap all span elements

But if there are many, you may want to do a little native DOM API:

var spans = document.getElementsByTagName('span');

while( spans[0] ) {
    var parent = spans[0].parentNode;
    while( spans[0].firstChild ) {
        parent.insertBefore( spans[0].firstChild, spans[0]);
    }
    parent.removeChild( spans[0] );
}

This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.

It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.

Community
  • 1
  • 1
user113716
  • 318,772
  • 63
  • 451
  • 440
  • 3
    nice... so mostly it revolves around the this keyword uneccessarily being wrapped into a jQuery object. – jondavidjohn Jan 10 '11 at 22:51
  • 1
    @jondavidjohn: Well, there are some fixes that are nice in some cases, like `this.value` where there are a couple browser quirks in certain cases. It all depends on your need. There are many nice techniques that are easy without jQuery, especially when performance is crucial. I'll try to think of more. – user113716 Jan 10 '11 at 22:53
  • 3
    I was about to write an answer but instead I'll add suggestions for yours. Generally, `attr()` is massively overused. If you're only dealing with one element then you'll rarely need `attr()`. Two of my favourites are the confusion around the `checked` property of checkboxes (all sorts of mystical incantations around that one: `$(this).attr("checked", "checked")`, `$(this).is(":checked")` etc.) and similarly the `selected` property of ` – Tim Down Jan 10 '11 at 23:01
  • @Tim Down: Ah yes, `checked` and `selected`. Hope you don't mind if I add those. – user113716 Jan 10 '11 at 23:05
  • 1
    Aaargh, @patrick, noooo: you've recommended `getAttribute()`. **You almost never need it**: it's broken in IE, doesn't always reflect the current state and it's not what jQuery does anyway. Just use properties. http://stackoverflow.com/questions/4456231/retrieving-html-attribute-values-the-dom-0-way/4456805#4456805 – Tim Down Jan 10 '11 at 23:05
  • @patrick: Re. `checked` and `selected`, please do. Also `disabled` and `readOnly`. And pretty much any Boolean property. – Tim Down Jan 10 '11 at 23:06
  • @Tim: If there's a direct map, yes, but if not, you need it. No? (Thinking of custom attributes.) – user113716 Jan 10 '11 at 23:08
  • There's a minor typo in your final example: you declare `var spans` but then refer to it as `span` in your loop. – keithjgrant Jan 10 '11 at 23:18
  • @patrick: True about custom attributes, although I never use them so I'm not an expert. I have a fog of mild anxiety in my mind about them, meaning it's something I need to look into. – Tim Down Jan 10 '11 at 23:26
  • 1
    I was using JS for so long and I didn't know about className, thx. – IAdapter Jan 11 '11 at 10:47
  • you can also add to the list `this.hash` – Luca Filosofi Jan 30 '11 at 16:28
  • @aSeptik: Ah yes, a glaring omission on my part. I plan on doing an update to this answer fairly soon. I'll be sure to include `hash` with credits to you. :o) – user113716 Jan 30 '11 at 16:53
  • `this.form` is great, then you can do `$(this.form).submit()`. No need for `$(this).closest('form').submit()` – Lime Jul 22 '11 at 20:28
  • @Lime: No need to wrap the form in a jQuery instance, just: `this.form.submit()` to submit the form. `submit` is a function of `HTMLFormElement` instances. – T.J. Crowder Jul 25 '11 at 17:16
  • @T.J. calling `submit()` directly fails to call any attached events. Therefore you can't use ajax on the form or cancel form submission because the events never fire. I specifically left the jQuery wrap. – Lime Jul 26 '11 at 02:36
66

The correct answer is that you'll always take a performance penalty when using jQuery instead of 'plain old' native JavaScript. That's because jQuery is a JavaScript Library. It is not some fancy new version of JavaScript.

The reason that jQuery is powerful is that it makes some things which are overly tedious in a cross-browser situation (AJAX is one of the best examples) and smooths over the inconsistencies between the myriad of available browsers and provides a consistent API. It also easily facilitates concepts like chaining, implied iteration, etc, to simplify working on groups of elements together.

Learning jQuery is no substitute for learning JavaScript. You should have a firm basis in the latter so that you fully appreciate what knowing the former is making easier for you.

-- Edited to encompass comments --

As the comments are quick to point out (and I agree with 100%) the statements above refer to benchmarking code. A 'native' JavaScript solution (assuming it is well written) will outperform a jQuery solution that accomplishes the same thing in nearly every case (I'd love to see an example otherwise). jQuery does speed up development time, which is a significant benefit which I do not mean to downplay. It facilitates easy to read, easy to follow code, which is more than some developers are capable of creating on their own.

In my opinion then, the answer depends on what you're attempting to achieve. If, as I presumed based on your reference to performance benefits, you're after the best possible speed out of your application, then using jQuery introduces overhead every time you call $(). If you're going for readability, consistency, cross browser compatibility, etc, then there are certainly reasons to favor jQuery over 'native' JavaScript.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • 1
    I know this is pedantic, but I'm not sure *"always"* is factual. – Stephen Jan 10 '11 at 22:01
  • 8
    I'd love to see an example of a situation where jQuery can outperform an implementation in pure JS. No matter what you do, if you're using jQuery (or any other library for that matter) you have function overhead that's unavoidable. There's no way to get away from the (albeit) minor overhead generated from calling `$()`. If you don't make that call, you save time. – g.d.d.c Jan 10 '11 at 22:03
  • 17
    A poorly written homemade solution would probably be slower. The jQuery team have executed some highly efficient JavaScript in the package. See @Freelancer's answer. – Stephen Jan 10 '11 at 22:12
  • 4
    A poorly written solution will always be a poorly written solution, and that's not the language's fault. It does not change the fact that the library will incur overhead that a 'native' function could avoid if well thought out. – g.d.d.c Jan 10 '11 at 22:14
  • 11
    @g.d.d.c. I think the best example where jQuery "outperforms" (read outside the benchmark box) pure JS is in cutting down dev time (that's a massive value business-wise) and simplifying experimentation – Ben Jan 10 '11 at 22:17
  • 13
    All of what you have written is true, but you have left off what @Ben notes above. jQuery makes the _developer_ faster and more robust. See [this KillClass() implementation](http://phrogz.net/JS/AddClassKillClass_js.txt) that I wrote many years ago and used heavily. You know what? It's _broken_ for certain edge cases. Poor code is poor code, and wrong code is wrong code, but using jQuery often makes the developer write better and more correct code. Most of the time, computers are fast enough; it's developers who need the help. – Phrogz Jan 10 '11 at 22:27
  • @Phrogz totally! On performance; the less we write, the less chance we have of doing things we perhaps didn't know were inefficient. I honestly don't know how to do a fraction of the things I can do in JS-sans-jQ than I can with jQuery so I know, if I tried, the dev. time and rubbish code would both lose to jQuery...so why bother? The same can be said for any progamming language (*I said it!*) and a higher-level language or wrapper/library for it. – Alastair Feb 08 '13 at 16:32
  • I think well thought out algorithm built into jQuery might be faster in some cases. For example, in [this question](http://stackoverflow.com/a/21445415/1256925), a bunch of answers were posted which all [ran slower than jQuery](http://jsperf.com/unique-in-array#results) in Chrome. The fact I then was able to make something that was indeed faster does mean your answer is still right, but if you don't use a well thought-out algorithm, it might just be slower. As shown by the "great" suggestions people posted there, which were actually slower. – Joeytje50 Dec 21 '14 at 13:55
41

There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)

So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.

Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.

On their homepage there's some perf comparisons:

enter image description here

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • 1
    @Leniel Macaferi Oh Man i loved this answer! I didn't realized that the performance between vanilla and other frameworks could make such a difference! Anyway Hall of fame for this answer!! P.S: Did you also made the website? – Steve Apr 19 '17 at 01:56
18

There's already an accepted answer but I believe no answer typed directly here can be comprehensive in its list of native javascript methods/attributes that has practically guaranteed cross-browser support. For that may I redirect you to quirksmode:

http://www.quirksmode.org/compatibility.html

It is perhaps the most comprehensive list of what works and what doesn't work on what browser anywhere. Pay particular attention to the DOM section. It is a lot to read but the point is not to read it all but to use it as a reference.

When I started seriously writing web apps I printed out all the DOM tables and hung them on the wall so that I know at a glance what is safe to use and what requires hacks. These days I just google something like quirksmode parentNode compatibility when I have doubts.

Like anything else, judgement is mostly a matter of experience. I wouldn't really recommend you to read the entire site and memorize all the issues to figure out when to use jQuery and when to use plain JS. Just be aware of the list. It's easy enough to search. With time you will develop an instinct of when plain JS is preferable.


PS: PPK (the author of the site) also has a very nice book that I do recommend reading

slebetman
  • 109,858
  • 19
  • 140
  • 171
14

When:

  1. you know that there is unflinching cross-browser support for what you are doing, and
  2. it is not significantly more code to type, and
  3. it is not significantly less readable, and
  4. you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:

use JavaScript. Otherwise use jQuery (if you can).

Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • 3
    I think the OP intends to use jQuery, but wonders where and when to use native JavaScript inside his jQuery methods. – Stephen Jan 10 '11 at 21:58
  • `.classList.remove('foo')` seems to work fine in newer browsers – Tyilo Dec 18 '11 at 12:58
  • 3
    @Tyilo classList.remove is part of HTML5 ClassList API that is not implemented in IE9 for example http://caniuse.com/#feat=classlist – corbacho Oct 28 '12 at 09:23
13

Others' answers have focused on the broad question of "jQuery vs. plain JS." Judging from your OP, I think you were simply wondering when it's better to use vanilla JS if you've already chosen to use jQuery. Your example is a perfect example of when you should use vanilla JS:

$(this).attr('id');

Is both slower and (in my opinion) less readable than:

this.id.

It's slower because you have to spin up a new JS object just to retrieve the attribute the jQuery way. Now, if you're going to be using $(this) to perform other operations, then by all means, store that jQuery object in a variable and operate with that. However, I've run into many situations where I just need an attribute from the element (like id or src).

Are there any other common practices like this? Where certain Javascript operations could be accomplished easier, without bringing jQuery into the mix. Or is this a rare case? (of a jQuery "shortcut" actually requiring more code)

I think the most common case is the one you describe in your post; people wrapping $(this) in a jQuery object unnecessarily. I see this most often with id and value (instead using $(this).val()).

Edit: Here's an article that explains why using jQuery in the attr() case is slower. Confession: stole it from the tag wiki, but I think it's worth mentioning for the question.

Edit again: Given the readability/performance implications of just accessing attributes directly, I'd say a good rule of thumb is probably to try to to use this.<attributename> when possible. There are probably some instances where this won't work because of browser inconsistencies, but it's probably better to try this first and fall back on jQuery if it doesn't work.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • hah, thanks for reading the question ;) ... so this is more broadly the exception? – jondavidjohn Jan 10 '11 at 22:15
  • @jondavidjohn: Honestly, I'm hesitant to make that call. I think yes, it's usually to your advantage to use jQuery due to cross-browser concerns. There are other examples, like `this.style.display = 'none'`. Is that better than `$(this).hide()`? I'd argue that the latter is more readable, but the former is likely faster. It doesn't hurt to do some experimenting yourself to see if certain actions will work across browsers without jQuery--This is typically what I do before wrapping an element in a jQuery object to perform an operation. – Andrew Whitaker Jan 10 '11 at 22:18
10

If you are mostly concerned about performance, your main example hits the nail on the head. Invoking jQuery unnecessarily or redundantly is, IMHO, the second main cause of slow performance (the first being poor DOM traversal).

It's not really an example of what you're looking for, but I see this so often that it bears mentioning: One of the best ways to speed up performance of your jQuery scripts is to cache jQuery objects, and/or use chaining:

// poor
$(this).animate({'opacity':'0'}, function() { $(this).remove(); });

// excellent
var element = $(this);
element.animate({'opacity':'0'}, function() { element.remove(); });

// poor
$('.something').load('url');
$('.something').show();

// excellent
var something = $('#container').children('p.something');
something.load('url').show();
Stephen
  • 18,827
  • 9
  • 60
  • 98
  • interesting... does this separation of var instantiation and action actually lead to processing performance gains? or just allows the action to execute on its own (making it less encumbered i guess...) – jondavidjohn Jan 10 '11 at 22:49
  • 1
    It most certainly leads to performance gains, but only if you re-use the selected element. So, in the last case `var something`, I didn't really need to cache the jQuery object (since I used chaining), but I do it anyway out of habit. – Stephen Jan 10 '11 at 22:52
  • 2
    On the other hand, take that same example. Calling `$('.something')` twice means that jQuery must traverse the DOM *twice* looking for all elements with that selector. – Stephen Jan 10 '11 at 22:56
  • 2
    In the case of the first example, caching `$(this)` reduces calls to the jQuery function. This will give you the most gain in a loop scenario. – Stephen Jan 10 '11 at 22:58
  • your first example is wrong - the animation complete call back will have `this` set to a single element (and will be called over and over) if the original `.animate()` function's selector covered more than one element. – Alnitak Jun 01 '12 at 17:39
  • 2
    @Alnitak Notice that `element` is equal to `$(this)`. That does not contain multiple elements. – Stephen Jun 03 '12 at 15:50
8

I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.

Dutchie432
  • 28,798
  • 20
  • 92
  • 109
6

This is my personal view, but as jQuery is JavaScript anyway, I think theoretically it cannot perform better than vanilla JS ever.

But practically it may perform better than hand-written JS, as one's hand-written code may be not as efficient as jQuery.

Bottom-line - for smaller stuff I tend to use vanilla JS, for JS intensive projects I like to use jQuery and not reinvent the wheel - it's also more productive.

sg7
  • 6,108
  • 2
  • 32
  • 40
CodeVirtuoso
  • 6,318
  • 12
  • 46
  • 62
  • 1
    There are lots of examples where libraries outperform vanilla JS. Many of the built-in prototype methods of JS are badly written, it turns out. – Union find Mar 01 '15 at 00:52
3

The first answer's live properties list of this as a DOM element is quite complete.

You may find also interesting to know some others.

When this is the document :

  • this.forms to get an HTMLCollection of the current document forms,
  • this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
  • this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
  • this.images to get an HTMLCollection of all the HTMLImageElements
  • and the same with the deprecated applets as this.applets

When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.

When this is a form :

  • this[inputNameOrId] to get the so named or identified field

When this is form field:

  • this.type to get the field type

When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.

atondelier
  • 2,424
  • 15
  • 11
  • The properties you mentioned are defined in the [DOM Level 2 HTML specification](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268), and widely supported. `document.embeds` and `document.plugins` are also widely supported (DOM 0). [`document.scripts`](https://developer.mozilla.org/en-US/docs/DOM/Document.scripts) is also a convenient collection, defined in the [HTML5 specification](http://www.w3.org/html/wg/drafts/html/master/dom.html#dom-document-scripts), and widely supported (and [Firefox 9+](https://developer.mozilla.org/en-US/docs/DOM/Document.scripts#Browser_compatibility)). – Rob W Mar 23 '13 at 18:12
  • @Robw So the list might now be complete, and definitely useful and fast. Thanks ;) – atondelier Mar 24 '13 at 16:58
3

As usual I'm coming late to this party.

It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.

It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.

I guess this sort of falls under the cross browser support/abstraction argument.

And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.

Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?

But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.

That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.

Swanny
  • 2,388
  • 17
  • 20
3

Here's a non-technical answer - many jobs may not allow certain libraries, such as jQuery.

In fact, In fact, Google doesn't allow jQuery in any of their code (nor React, because it's owned by Facebook), which you might not have known until the interviewer says "Sorry, but you cant use jQuery, it's not on the approved list at XYZ Corporation". Vanilla JavaScript works absolutely everywhere, every time, and will never give you this problem. If you rely on a library yes you get speed and ease, but you lose universality.

Also, speaking of interviewing, the other downside is that if you say you need to use a library to solve a JavaScript problem during a code quiz, it comes across like you don't actually understand the problem, which looks kinda bad. Whereas if you solve it in raw vanilla JavaScript it demonstrates that you actually understand and can solve every part of whatever problem they throw in front of you.

sg7
  • 6,108
  • 2
  • 32
  • 40
Jack Connor
  • 111
  • 3
1

$(this) is different to this :

By using $(this) you are ensuring the jQuery prototype is being passed onto the object.

antyrat
  • 27,479
  • 9
  • 75
  • 76
John Green
  • 11
  • 1