Martin
Martin

Reputation: 24316

Getting array index of "children" doesn't allow further jQuery use

I have the following, and it appears to work:

$(element).parent().children('ul').children('li').children('a:first').attr('href')

this selects the first li but I wanted to do this:

$(element).parent().children('ul').children('li')[1].children('a:first').attr('href')

So I can pass in the index number but doing this gives me an error:

TypeError: Property 'children' of object #<HTMLLIElement> is not a function

Upvotes: 1

Views: 155

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115262

children('li')[1] will return a dom object ,hence to select first item use eq() method

$(element).parent().children('ul').children('li').eq(0).children('a:first').attr('href')

Upvotes: 4

reergymerej
reergymerej

Reputation: 2417

When you use first() you're getting a raw HTML element.

// returns a jQuery collection of li elements
$('li');

// returns the first item in the collection, which is just an li
$('li').first();

first() documentation

To keep chaining jQuery methods, you'll want to get the first item, not as raw HTML, but as a jQuery object.

// returns the first item in the collection as a jQuery object
$('li').eq(0);

eq() documentation

Upvotes: 0

jaime1985
jaime1985

Reputation: 16

When you give the index that dont return a jquery object you need to do like this

 $($(element).parent().children('ul').children('li')[1]).children('a:first').attr('href')

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82251

You need .eq selector:

$(element).parent().children('ul').children('li').eq(0).children('a:first').attr('href');

eq(0) will select the first li element.

see docs

Upvotes: 1

Related Questions