tags:

views:

55

answers:

3

In my code when I write code like:

$("#id_pop")[0]

there is an error. When I correct it to:

var $d = $("#id_pop");
$d[0]....

it's ok. Why?

+3  A: 

[0] should work, i.e. get you a DOM object. But you can't continue using jQuery methods once you get back a normal DOM object.

you can also get a DOM object from a jQuery selector like this:

$('#id_pop').get(0);

Also are you sure you only have one element with the id id_pop. If there is then $('#id_pop')[0] should work.

See working example here: http://jsbin.com/udace3

Moin Zaman
can you explain why [0] not working?
Bin Chen
see my updated answer
Moin Zaman
I see! so $d is still an jquery object but if I only get it from [0] it is a normal dom object, that is why the error is happening.
Bin Chen
+1  A: 

You are using an ID selector, you should not be getting an array but the jquery object itself. In the jQuery documentation of using the #id,

Each id should only be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on...

Manny
A: 

Isn't it better to use .eq() instead of .get()?

$('#id_pop').eq(0);

Or for that matter:

$('#id_pop:eq(0)');
bozdoz
both of these are still jQuery objects and not plain JS DOM objects
Moin Zaman
True, but he's using jQuery, so I suggested it.
bozdoz