When to use Vanilla JavaScript vs. jQuery?

jondavidjohn picture jondavidjohn · Jan 10, 2011 · Viewed 71.9k times · Source

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.

Answer

user113716 picture user113716 · Jan 10, 2011
  • 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: