nth Child Selector
Instead of defining how nth chiild selector work, we will proceed by example. Let us assume thae your have a webpage that has a heirarchy. A typical heirarchy may consist of for example, header element and then paragraphs. If we wish to select every <h;p> element that is the second child of its parent element, then we can do it using
$("p:nth-child(2)")
Let us take a look at the example
<!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> $(document).ready(function(){ $("a:nth-child(2)").css("background-color","pink"); }); </script> </head> <body> <h1>Reference Designer jQuery nth-child example</h1> <a href ="http://referencedesigner.com">Link1 - second chile of body </a><br /> <a href ="http://www.referencedesigner.com/tutorials/jquery/jq_1.php">Link2 - jquery tutorial - 3rd child of body </a><br /> <br /> <div style="border:2px solid;"> <span> span element in 1st div</span> <a href ="http://referencedesigner.com"> Link1 - second child of div </a> <a href ="http://www.referencedesigner.com/tutorials/js/js_1.php"> Link2 - js tutorial </a> <a href ="http://referencedesigner.com"> ReferenceDesigner</a> </div><br> <div style="border:1px solid;"> <a href ="http://referencedesigner.com"> Link1 - 1st child of second div </a> <a href ="http://www.referencedesigner.com/tutorials/js/js_1.php"> 2nd child - js tutorial </a> <a href ="http://referencedesigner.com"> ReferenceDesigner</a> </div> <div> <h1> second header </h1> <p>Para1</p> <p>Para 2</p> <p>Para 3</p> </div> </body> </html> |
You may like to make changes in the index in the above example to see the effects.
You may like to try this example here.