Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'... 
like image 761
Todd Vance Avatar asked May 12 '11 19:05

Todd Vance


People also ask

How do you use the nth child in querySelector?

To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.

How do you use the nth child in sass?

Writing Complex :nth-child() SelectorsIt works exactly the same as :nth-child except that it starts from the end of the parent. For example, you can select the first three children of a parent by using the selector :nth-child(-n + 3) . You can use :nth-last-child(-n + 3) to select the last three.

How do you use the nth of a child?

Definition and UsageThe :nth-child(n) selector matches every element that is the nth child of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-of-type() selector to select the element that is the nth child, of the same type (tag name), of its parent.

How do you find the nth child of an element?

Use the querySelector() method to get the nth child of an element, e.g. document. querySelector('#parent :nth-child(3)') . The :nth-child pseudo class returns the element that matches the provided position.


1 Answers

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'); 
like image 171
kapa Avatar answered Oct 22 '22 09:10

kapa