Hello all,
Working with JQuery, many times we tries to search a particular parent element which may be a specific HTML tag (like div, para any other tag), and to do this, JQuery comes with some built-in function which allows us to find the parent element , which are :
- $(Your selector).closest(Any HTML element);
- $(Your selector).parents(Any HTML element)
But there are some deference between both of these functions.
closest() function will return the first ancestor of matching type while traversing upwards from the current element to the root level that is <html>, where as the parents() function will return all the matching ancestor while traversing upwards from the current element to the root level that is <html>.
To understand this lets consider an example :
In HTML, we have :
<html>
<head>
<title>JS Test Page</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
<script src="JSFile.js">
</head>
<body>
<div id="mainDIv">
<div id="innerDiv">
<table border="1" cellpadding="10">
<tr>
<td>
<ul style="margin:50px 50px 50px 30px;">
<li><a id="closetAnchor" href="#" onclick="getCloset
(this);">Get Closet</a></li>
<br>
<li><a id="parentAnchor" href="#" onclick="getParent
(this);">Get Parent</a></li>
</ul>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
In JavaScript we have :
function getCloset(ele) {
var closetElement = $(ele).closest('Div');
if (closetElement.length > 0) {
for (var i = 0; i < closetElement.length; i++) {
alert(closetElement[i].id);
}
}
}
function getParent(ele) {
var parentElement = $(ele).parents('Div');
if (parentElement.length > 0) {
for (var j = 0; j < parentElement.length; j++) {
alert(parentElement[j].id);
}
}
}
In the above example if we click on Get Closet link, than it will give one alert for one time with innerDiv as the .closest(); function return first matching ancestor while on clicking Get Parent link we will get alert for two times that is innerDiv and mainDiv as the .parents() function array of all the matching ancestors.
0 Comment(s)