jQuery
Selecting First Level Child Using :first-child Selector In jQuery
If you have many elements in a web page but need to select only the first one among them and perform your operation on it, what would you do? If you don’t have an answer, then this article is for you. In this article, I am going to share very easy way to perform operations on the first level child of any desired element. So read on to find out more.
How To Use :first-child Selector
The first-child selector basically selects all elements that are the first child of their parent.
Let’s take a look at a quick example. The following is the HTML Source code used in the examples.
<div class="divs_container"> <div id="my_div1">This is My Div 1.</div> <div id="my_div2">This is My Div 2.</div> <div id="my_div3">This is My Div 3.</div> <div id="my_div4" class="new_div">This is My Div 4 <p id="p1">Para 1</p> <p id="p2">Para 2</p> <p id="p3">Para 3</p> </div> <br> <table width="100%" border="1" cellspacing="1" cellpadding="1"> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> </div> <p> <input type="submit" name="sbt_add1" id="sbt_add1" value="Add Class to First Div Child"> <input type="submit" name="sbt_add2" id="sbt_add2" value="Add Class to First p child"><br> <input type="submit" name="sbt_add3" id="sbt_add3" value="Add Class to First child of Table"> <br> <input type="button" name="sbt_reset" id="sbt_reset" value="Reset everything"> </p>
Example 1: Select first level child div and add custom class to it when a button is clicked
$('#sbt_add1').on("click", function(e){ $('.divs_container div:first-child').addClass('purple'); e.preventDefault(); });
Example 2: Select first level child p tag and add custom class to it when a button is clicked
$('#sbt_add2').on("click", function(e){ $('.divs_container p:first-child').addClass('purple'); e.preventDefault(); });
Example 3: Select first level child table cell and add custom class to it when a button is clicked
$('#sbt_add3').on("click", function(e){ $('.divs_container table td:first-child').addClass('purple'); e.preventDefault(); });
Simple, isn’t it?
Do you know of any other ways to use the :first-child selector in jQuery? Feel free to suggest by commenting below.