The jQuery JavaScript library allows you to select any element on a webpage and modify it. I will assume you already know how it works, or at least what it’s for. Now, say you have a table containing the following:
<tr id="123" class="employee">
<td class="name">John Smit</td>
<td><img src="..." class="image" /></td>
</tr>
<tr id="983" class="employee">
<td class="name">Juan Smith</td>
<td><img src="..." class="image" /></td>
</tr>
<tr id="219" class="superhero">
<td class="name">Mr. Incredible</td>
<td><img src="..." class="image" /></td>
</tr>
Selecting only the employee elements (assuming that the class “employee” is not used elsewhere) can be done via ‘$(“.employee”)’. For example:
$(".employee").css("color", "red");
would set the names of both employees to red. Similarly, it’s easy enough to select a specific row and hide the person’s name:
$("#219.name").hide();
But what if you have a situation where a certain element is being passed to your function as an object? You have the variable ‘myRow’, for example; and it’s an unknown (to you) element on your page. And now you want to hide only the image within that row. You don’t know the id you’ve been given, you just have the object. Even if you get the object’s id out via myRow.attr(“id”), how can you pass it to your jQuery selector? And how can you select and hide the image? Using something like
$("#219.image").hide();
would not work, because (even assuming you get the ID in there somehow) the “image” element is two levels down. The row with id 219 does not have a child of the “image” class. It has a classless child which in turn has a child of the “image” class. So the selector “#219.image” will return nothing. This seems like quite the unsolvable problem. (EDIT: see the comments for a way to do this without jQuery as suggested by Barry Rowlingson.)
It turns out that jQuery already has a neat, pre-packaged solution for this conundrum. It’s the .find() function, and in our example, it could be used like this:
myRow.find(".image").hide();
Very simple, and very useful! Pass it an element on your page, and you can select any child of a given class.
