Is there a way to combine $(this) with :nth-child?
Asked Answered
I

1

35

I'm in the middle of an .each iteration and wanted to call out the 2nd or 3rd child for the each..but cant make it work.

alert($(this + ' :nth-child(2)').attr('id'));

My only option that I can think of is something terrible goofy like this:

 $(this).children(':first').next().attr('id', 'ddParam' + newCount);
 $(this).children(':first').next().next().attr('id', 'txt' + newCount);
 $(this).children(':first').next().next().next().attr('id'...
Illlooking answered 12/5, 2011 at 19:34 Comment(3)
Have you tried $(this).find(':nth-child(2)')?Exoteric
I hadnt, but now I have and it didnt produce any results.. Thanks thoughIlllooking
my bad - haha... child #2 in my case has no ID (thus a blank return)Illlooking
A
76

What you need is context. With context, the selector will only look for elements that are the children of the context (in this case this).

$(':nth-child(2)', this).attr('id');

jsFiddle Demo

This is basically the same as:

$(this).find(':nth-child(2)').attr('id');

If you only need the direct children, not every descendant, you should use .children():

$(this).children(':nth-child(2)').attr('id');
Atingle answered 12/5, 2011 at 19:39 Comment(3)
alert($(':nth-child(1)', $(this)).attr('id')); -- thanks, but this produces nothing for me... any thoughts?Illlooking
@toddv Oh, I had a mistake, fixed. I added a jsFiddle to let you test this.Atingle
Whoops.. my child #2 had no id -- thus a blank popup --- sry. THANKS FOR THE ANSWER!Illlooking

© 2022 - 2024 — McMap. All rights reserved.