Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
230,995 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 ?