Reputation: 24316
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
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
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();
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);
Upvotes: 0
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
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.
Upvotes: 1