1

So I have a simple html page:

<h1>Start</h1>
<canvas class="myCanvas" width="400" height="400"></canvas>
<canvas class="myCanvas" width="400" height="400"></canvas>

And in jquery I do,

> $(".myCanvas")
| [<canvas class=​"myCanvas" width=​"400" height=​"400">​, 
|  <canvas class=​"myCanvas" width=​"400" height=​"400">​]

And then,

> $(".myCanvas").first()
| [<canvas class=​"myCanvas" width=​"400" height=​"400">​]

I thought I should get a single element in the call to the first() method, like in

> $(".myCanvas").get(0)
| <canvas class=​"myCanvas" width=​"400" height=​"400">​

So why does the first method return an array..?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dhruv Kapur
  • 726
  • 1
  • 8
  • 24

3 Answers3

6

The .first() method filters the result set to the first element and returns a jQuery object, while .get(0) simply returns the first DOM element.

The reason the jQuery object displays as an array is because jQuery objects act as enhanced arrays of DOM elements with additional methods on their prototype. For that reason, .get(0) is really just the same as [0].

Alexis King
  • 43,109
  • 15
  • 131
  • 205
1

I thought I should get a single element in the call to the first() method

No, first does return a jQuery collection (with the one first element only, or even no element at all), so that you can call further jQuery methods on it. Notice that it does not return an Array, but just some special array-like object.

In contrast, get returns the first DOM element in the collection or undefined.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Quoting Documentation:

Reduce the set of matched elements to the first in the set.

haim770
  • 48,394
  • 7
  • 105
  • 133