Closest
Search your ancestors for elements that match the past selector, as you indicated. In other words, search for elements that are up .
Consider the following structure:
<table>
<tr>
<td><a href="#">Link 1</a></td>
<td><a href="#">Link 2</a></td>
</tr>
<tr>
<td><a href="#">Link 3</a></td>
<td><a href="#">Link 4</a></td>
</tr>
</table>
Now imagine that every time you click on a <a>
, the color of the <tr>
in which it is inserted changes. In this case closest("tr")
gives exactly the <tr>
closest up DOM:
$("a").on("click", function(){
$(this).closest("tr").toggleClass("cor");
});
.cor {
background-color:cyan;
}
td {
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><ahref="#">Link 1</a></td>
<td><a href="#">Link 2</a></td>
</tr>
<tr>
<td><a href="#">Link 3</a></td>
<td><a href="#">Link 4</a></td>
</tr>
</table>
Note that changing this closest
to find
will not work because find
only looks at the children of the element where the search begins. Then doing $(this).find
in <a>
will look at the descendant / child elements of <a>
where there will be no <tr>
.
See how does not work :
$("a").on("click", function(){
$(this).find("tr").toggleClass("cor");
});
.cor {
background-color:cyan;
}
td {
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><ahref="#">Link 1</a></td>
<td><a href="#">Link 2</a></td>
</tr>
<tr>
<td><a href="#">Link 3</a></td>
<td><a href="#">Link 4</a></td>
</tr>
</table>
Documentation for closest
Find
This method is used when you need to find descendants / children elements, which match the indicated selector.
$("tr").on("click", function(){
$(this).find("a").toggleClass("cor");
});
.cor {
background-color:cyan;
}
td {
padding:10px;
}
tr {
background-color:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><ahref="#">Link 1</a></td>
<td><a href="#">Link 2</a></td>
</tr>
<tr>
<td><a href="#">Link 3</a></td>
<td><a href="#">Link 4</a></td>
</tr>
</table>
I slightly changed the style to make it clear that you just need to click on the gray area, which is the area covered by <tr>
.
In this case you can not change <a>
by <tr>
otherwise the code will try to find a find
that is above closest
that there are none.
Same example with <a>
to see that does not work :
$("tr").on("click", function(){
$(this).closest("a").toggleClass("cor");
});
.cor {
background-color:cyan;
}
td {
padding:10px;
}
tr {
background-color:gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><td><ahref="#">Link 1</a></td>
<td><a href="#">Link 2</a></td>
</tr>
<tr>
<td><a href="#">Link 3</a></td>
<td><a href="#">Link 4</a></td>
</tr>
</table>
Documentation for <tr>