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 jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 4

Please, explain me!

Why do we need assign in brackets zero?

$("canvas")[0].getContext("2d");

2 Answers

Sean T. Unwin
Sean T. Unwin
28,690 Points

$('canvas') is a jQuery object which is in turn an array-like object (it has a length therefore it can be indexed) which will hold an array of all canvas objects in the document.

In order to access the Canvas API we need to get to the raw element. To do this, when an element representation is encased within a jQuery object, we use Array notation because the raw element is the first item in a jQuery object. A jQuery object is a collection of elements where each are able to be accessed by an array index.

In the case of $("canvas")[0] we are getting the canvas element which appears first in the DOM, i.e. closest to the opening body tag. If there was a second canvas and we needed to access it we would use $('canvas')[1].

View an example illustrating this on Codepen.

Sean, I was able to follow your explanation above, well said. I did try to follow your code pen example and got pretty lost there though. Liked what you did anyway.

Aaron Selonke
Aaron Selonke
10,323 Points

In the codepen example, What undesirable behavior is the preventDefault() method preventing?

Blake Lieberman
Blake Lieberman
23,772 Points

My best bet is $('canvas') returns an array with one entry. $('canvas')[0] equals the first canvas element in the array.