jQuery this selector

We will try now to understand the concept of referencing using this . Do not get discouraged if you do not understand the whole concept. But you should be able to understand the underlying concept in the example that we will provide.

When we call the jQuery Anonymous function, we call it calls the function for each occurence of the matching selection. At each selection we perform some action. The this keyword refers to whatever element is calling the anonymous function. So the first time through the loop, this refers to the first element in the jQuery selection, while the second time through the loop, this refers to the second element. to convert this to its jQuery equivalent, you write $(this)

find selector

We will now understand the find selector before we present an example that explains this as well as the find selector.

The .find() selector finds particular elements inside the current selection. As an example

find("tr").css("background-color", "gainsboro");

finds all of rows inside a table and changes the background color of the row to gainsboro.

You use .find() to select a descendent (a tag inside another tag) of the current selection. Now take a look at the following example

The following example highlights all the rows of a table that contains a link


<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script>

$(document).ready(function(){
     $("#parent").click(function(){
    $(this).find("tr").css("background-color", "gainsboro");

    });
    });
 </script>
<body>

<h1>List of Cars </h1>

<table id ="parent" border=1 >
     <tr>
      <td>Make</td>
      <td>Model</td>
    </tr>
    <tr>
      <td>Toyota</td>
      <td>Corolla</td>
    </tr>
    <tr>
      <td>Honda </td>
      <td>Civic</td>
    </tr>
    <tr>
      <td>Ford </td>
      <td>Focus</td>
    </tr>
</table>

</body>
</html>



You may like to try this example here.

Pay attention to the usage of $(this) in

$(this).find("tr").css("background-color", "gainsboro");

It $(this) here refers to the table with id parent. The rest of the code should be easy to understand.

As an exercise you may want to modify the example so that it makes use of contains .