jQuery
Selecting First Element Of Type Using :first-of-type Selector in jQuery
The :first-of-type selector is another helpful selector in jQuery. It basically selects all elements that are the first among siblings of the same element name. That said, let’s take a look at quick examples on how to use it in real time to select any element that we need.
How To Use the first-of-type Selector in jQuery
Let’s take a look at a quick example. The following is the HTML Source code used in the examples.
<style type="text/css"> #my_div { background-color: #DBF0FF; border: 1px solid #06F; } .new_div { background-color: #FFDF9D; border: 1px solid #F90; } .purple { background-color: #9999FF; border: 1px solid #90F; } table td { border: 1px solid #CCC; } </style> <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 <span id="sp1">Span 1</span> <p id="p1">Para 1</p> <span id="sp2">Span 2</span> <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"> <input type="submit" name="sbt_add2" id="sbt_add2" value="Add Class to First p"> <input type="submit" name="sbt_add2" id="sbt_add3" value="Add Class to First span"><br> <input type="submit" name="sbt_add3" id="sbt_add4" value="Add Class to First td of Table"> </p>
Example 1: Select first element of type div and adding custom class to it when a button is clicked
$('#sbt_add1').on("click", function(e){ $('.divs_container div:first-of-type').addClass('purple'); e.preventDefault(); });
Example 2: Select first element of type p and adding custom class to it when a button is clicked
$('#sbt_add2').on("click", function(e){ $('.divs_container p:first-of-type').addClass('purple'); e.preventDefault(); });
Example 3: Select first element of type span and adding custom class to it when a button is clicked
$('#sbt_add3').on("click", function(e){ $('.divs_container span:first-of-type').addClass('purple'); e.preventDefault(); });
Example 4: Select first element of type td and adding custom class to it when a button is clicked
$('#sbt_add4').on("click", function(e){ $('.divs_container table td:first-of-type').addClass('purple'); e.preventDefault(); });
Simple, isn’t it?
Do you know of any other ways to use the :first-of-type selector in jQuery? Feel free to suggest by commenting below.