4

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/

2

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

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

or

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

or

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

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.