Question

This doesn't work when I run it in my Chrome console:

($('.myClass > ul > li > a'))[0].closest('li')

TypeError: Object [object HTMLAnchorElement] has no method 'closest'

I thought $('.myClass > ul > li > a') returned an array of jquery objects, but dir($('.myClass > ul > li > a')) shows me it is a single jquery object. Is there an simple way to index into the jquery object like this and call methods on the elements when I'm just farting around in the console? Or am I missing something fundamental about how jquery works?

Était-ce utile?

La solution

I thought $('.myClass > ul > li > a') returned an array of jquery objects

That's where the misunderstanding is. It doesn't return an array of jQuery objects, it returns a single jQuery object. That object is a pseudo-array (in this case of DOM elements; jQuery objects can contain other things, but 99% of the time they contain DOM elements). So [0] gives you a DOM element, not a jQuery object, which has no closest method.

If you want the first one, use jQuery's first() or eq(0) methods, which give you the first element wrapped in a jQuery object, or if you like get the element with [0] then use $() to wrap it.

// first:
$('.myClass > ul > li > a').first().closest('li')
// eq(0):
$('.myClass > ul > li > a').eq(0).closest('li')
// The long way (I wouldn't do this, just be comprehensive)
$($('.myClass > ul > li > a')[0]).closest('li')

You can also use jQuery's :first selector enhancement:

$('.myClass > ul > li > a:first').closest('li')

...but doing so means jQuery can't hand off to the browser's own query selector.

Autres conseils

You are trying to use a jQuery function on a DOM object you must use .eq() to get the index

$('.myClass > ul > li > a').eq(0).closest('li') 

[0] returns a DOM object.

Try doing this instead:

$('.myClass > ul > li > a').eq(0).closest('li')

You would need to access the array item again via jquery to use the closest method like so...

$($('.myClass > ul > li > a')[0]).closest('li');

or... You could use a selector...

$('.myClass > ul > li > a').first().closest('li');

You need to use eq() selector.When you access an item from a collection with a subscript like [i], you're actually unwrapping it from the jQuery object, and accessing a raw DOM node, which doesn't have methods like closest.

$('.myClass > ul > li > a').eq(0).closest('li')

You can use the following code..

$('.myClass')
    .children('ul')
    .children('li')
    .children('a')
    .eq(0)
    .closest('li')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top