FYI: $("..") vs document.getElementById("..")

Posted by Katie McLaughlin on September 11, 2014

I'm often confused by things I don't understand (like ducks). However, once I get an idea about the reasoning behind things, it makes it easier to remember.

An example: the difference between $("..") and document.getElementById("..")

Say you have a div with an id of thing. You can use javascript to assign the variable myThing to a node defined by the id thing via a few methods:

  • `document.getElementById("thing")`. This will return a node.
  • `$("#thing")`. This will NOT return a node. It will return a jQuery "array" of objects with extra wrappers for helpful functions. 

If you want the node only in jQuery, or the shortest amount of characters possible, then use $("#thing")[0]

Note the addition of # in the jQuery calls. This is because you use # for ids, and you don't use it in the case where you are explicitly asking for "the element with the ID known as" (in the case of getElementById). Also, you use[0] # for ID and . for classes in CSS, so it's totally consistent. (A fun mnemonic if you can't remember the difference: "ID Number, ID #")

 [0] used, some CSS linters get upset at using # for ID now. This is probably for a reason, but outside of the scope of this braindump.