Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return array of jQuery object with selector

Tags:

jquery

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/

like image 887
TonyTakeshi Avatar asked Dec 07 '22 14:12

TonyTakeshi


2 Answers

.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.

like image 182
ThiefMaster Avatar answered Dec 31 '22 15:12

ThiefMaster


$('#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

like image 39
LoneWOLFs Avatar answered Dec 31 '22 16:12

LoneWOLFs