Find nth:child element in its parent using jQuery
jQuery API provides a selector ":nth-child" which allows to select particular child element from its parent. For example, if you want to select 2nd li element from the ul tag. See below code.
<ul> <li>jQuery</li> <li>By</li> <li>Example</li> </ul>
This code will find the 1st li element and makes it forecolor to "Red". For 2nd li element its green and for 3rd li element its blue.
$(function() { $('ul li:nth-child(1)').css('color', 'Red'); $('ul li:nth-child(2)').css('color', 'Green'); $('ul li:nth-child(3)').css('color', 'blue'); });
Result:
This selector accepts four different values.
- index:Selects a single column with the specified numeric index. Remember, with :nth-child function the index starts from 1.
$('ul li:nth-child(1)').css('color', 'Red');
- even:This option selects all the even child element in the parent.
$('ul li:nth-child(even)').css('color', 'blue');
- odd:This option selects all the odd child element in the parent.
$('ul li:nth-child(odd)').css('color', 'blue');
- equation:equation could be a*n or a*n + b where a and b both can be +ve or -ve value. n represents the column index. Below code will select items like 3,6,9 etc...
$('ul li:nth-child(3n)').css('color', 'blue');
Below code will splits the elements in group with size of 3 and selects 1 element in that list.
$('ul li:nth-child(3n+1)').css('color', 'blue');
both a and b are optional, but at least one should be provided.
You can also use this function with table tag. Below code finds 3rd td of table with id "tbl".
$('#tbl tr td:nth-child(3)').css('color', 'Red');
Feel free to contact me for any help related to jQuery. I will gladly help you.