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'...
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.
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With