TonyTakeshi
TonyTakeshi

Reputation: 5929

How to return array of jQuery object with selector

I am trying to retrieve an array of jquery object from selector, so I would not have to re-query them again for modification later.

But, while I testing with the code, I find that the jquery selector returns array as html element if it does not query specific element.

//HTML
<div id='nav'>
    <div class='menu'>menu 1</div>
    <div class='menu'>menu 2</div>
    <div class='menu'>menu 3</div>
    <div class='menu'>menu 4</div>
    <div class='menu'>menu 5</div>
</div>​


//JS

//this works
$('#nav .menu:eq(0)').html('haha');

//this does not    
$('#nav .menu').get(0).html('halo w');​ 

-> Uncaught TypeError: Object #<HTMLDivElement> has no method 'html'

My question is why does it return html element and not jquery object.How can I retrieve an array of jquery objects from selector.

Here's the JSFiddle example.

http://jsfiddle.net/mochatony/K5fJu/7/

Upvotes: 4

Views: 20980

Answers (3)

LoneWOLFs
LoneWOLFs

Reputation: 2306

$('#nav .menu') does return an array of the matched elements. But to use it you have to access it properly. Consider the following code

var x = $('#nav .menu'); //returns the matching elements in an array

//(recreate jQuery object)
$(x[1]).html('Hello'); //you can access the various elements using x[0],x[1] etc.

above is same as

$($('#nav .menu')[1]).html('Hello');​

If you do a alert(x.length) u'll get 5 as an alert which indicates the length of the array as per your example.

JSFIDDLE Example

Upvotes: 4

thecodeparadox
thecodeparadox

Reputation: 87073

$('#nav .menu:eq(0)');

or

$('#nav .menu:first');

or

$('#nav .menu').first();

or

$('#nav .menu').eq(0);

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318518

.get(i) returns the DOM element. What you want is one of these:

$('#nav .menu').first()
$('#nav .menu').eq(0)

See http://api.jquery.com/category/traversing/filtering/ for a list of possible filter functions.

Upvotes: 11

Related Questions