How to return jQuery object array with selector

I'm trying to get an array of jquery object from a selector, so I don't have to re-query them again to change later.

But while testing the code, I found that the jquery selector returns an array as an html element if it does not request a 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 it returns an html element, not a jquery object. How can I get an array of jquery objects from a selector.

Here is an example JSFiddle.

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

+3
source share
3 answers

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

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

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

+9

$('#nav .menu') . .

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.

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

alert(x.length), 5 , .

JSFIDDLE

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

or

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

or

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

or

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

All Articles