A question about $ function

Hi guys,

I’m studying Javascript and I read a $ function like this


var $ = function(id){
     return document.getElementById(id);
}

According the book, it says this is shortcut for the document.getElementById method. I can’t understand why is that?? why not use document.getElementById(“id”) directly? and instead of this, creating a $ function and then call the function? what’s the benefit for this??

With jQuery you can put any CSS selector in the $ function and it will return the matched elements. Even complex queries like this:

$('#wrapper div:first-child:not(.section) > span ~ a[href^=mailto]');

For more info, look at the jQuery documentation for the function.

Here’s the jQuery documentation about its selectors.

I see. For additional ways, do you mean the methods being able to access specific node or certain parent node’s children, something like that? If it’s not, would you mind give me some clues so that I will know where I can find and study it. Thx.

Essentially, yes, however jQuery has additional ways you can work with selecting elements using the $

So is it with the same meaning that using Jquery?? If I have linked Jquery lib, then I can do the same thing and without create a $ function. Am I right??

document.getElementById() is perhaps the most commonly used call in JavaScript. Since just about any script can potentially contain dozens of such calls it makes sense to provide a shorter name that can be used to perform that processing. A single character function name is as short as you can get and $ was considered to be the one character that is least likely to be used as a single letter function name in existing scripts.

It’s shorthand. It’s shorter and simpler to use. Less code to type. Less data to transfer when a page is loaded.