Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Akhter Rasool
Akhter Rasool
8,597 Points

//$("canvas")[0]

why are we using [0] in front of the selector??

Also please tell me the difference between caching items to a jquery object($context) and a variable(context) ??

1 Answer

Steven Parker
Steven Parker
215,939 Points
//$("canvas")[0]

The two slashes (//) makes this a comment, it does nothing. But without the slashes, $("canvas") returns a set of objects representing all canvas elements. The [0] after it gives you the first (and possibly only) single element from that set.

The only difference between "$canvas" and "canvas" is the "$" in the name, they are both variables. Either one can be assigned with a JQuery object. It's just a commonly used (and recommended) convention to use variable names that begin with $ to represent JQuery objects.

Akhter Rasool
Akhter Rasool
8,597 Points

so will $canvas and canvas have same functionality? if yes, then which one do i use in a situation ?