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/
.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.
$('#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With