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 trialGrace Ji
5,402 PointsWhat is [0] behind $("canvas")?
Andrew made var context = $("canvas")[0].getContext("2d"); what is [0] for?
2 Answers
Benjamin Larson
34,055 Points[0]
is an array index to select the first item item in the array since array indexes start are 0. The $('canvas')
selector with return an array of all canvas elements in the HTML. Even if there is only 1, it will still be an array of just 1 item, and will need to be accessed with an index.
Grace Ji
5,402 PointsThank you Benjamin! I can totally understand with the $('p') example now. You rock!
Grace Ji
5,402 PointsGrace Ji
5,402 Pointsso [0] indicates where the canvas begins first?
Benjamin Larson
34,055 PointsBenjamin Larson
34,055 PointsNot quite. It selects the first
<canvas>
element that appears in the HTML. In this instance there is only 1, but if there were more canvas elements, you would use[0]
to select the first one, [1] to select the second, and so on.It might make more sense if you think about the selector
$('p')
. This would select all the paragraphs on a page (of which there could be many) and store them in an array. This is helpful if you wanted to make a change to ALL of the paragraphs at once, but if you only wanted to make a change to the first paragraph, you would have to make you selection more specific by using the array index$('p')[0]
.Normally if you are trying to select just 1 of something, you would probably give it an id and use that for your selector with something like:
('#myCanvas')