Akhil Sekharan
Akhil Sekharan

Reputation: 12693

Is jQuery's $(selector).eq(index) and $(selector)[index] the same?

What is the difference between all these ways?

//1
$('div').eq(index) 

//2
$('div')[index] 

//3
$($('div')[index] )

//4
$('div').get(1)

Are they same?

ScreenShot

Upvotes: 3

Views: 1258

Answers (4)

VisioN
VisioN

Reputation: 145418

No.

The first and the third return jQuery object, while the second and the forth return DOM element:

$("div").eq(index) === $($("div")[index]);  // --> jQuery object

$("div")[index] === $("div").get(index);    // --> DOM element

You can read about the last case here: http://api.jquery.com/get/.

If you need to see the difference between types you may try to run the following in the console:

Object.prototype.toString.call($("div").eq(index)); // "[object Object]"
Object.prototype.toString.call($("div")[index]);    // "[object HTMLDivElement]"

Upvotes: 5

Adil
Adil

Reputation: 148150

First and third will get you jQuery object and second one will give you DOM object.

  1. $('div').eq(index) // will return jquery object

  2. $('div')[index] // will give you javascript DOM object

  3. $($('div')[index]) //will give you jQuery object by converting DOM object

You require different syntax to get the properties for instance for id of object.

idofobject = $('div').eq(index).attr('id') //jQuery

idofobject = $('div')[index].id            //javascript

Upvotes: 3

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

  • v1: $('div').eq(index) :: returns a jQuery-wrapped collection comprising one div.

  • v2: $('div')[index] :: returns a reference to a DOM element (not jQuery-wrapped)

  • v3: $($('div')[index]) :: returns a jQuery-wrapped collection comprising one div. This is a verbose and inefficient version of the v1.

You didn't ask about $('div').get(index), which is another way of achieving v2. AFAIK, it is not substantially less efficient.

Upvotes: 1

DDK
DDK

Reputation: 1038

$('div').eq(index) This returns a JQuery object

$('div')[index] this will give you javascript object

Upvotes: 2

Related Questions