Below code clarify some differences between the parent() and parents() methods.
parent(selector) : This returns the one immediate parent of the element. Selector is passed in only required cases, like if we want to check if parent exists for the element or in some other situations. Here is simple example which illustrates the parent method.
parents(selector) : This returns the multiple ancestors. Its not restricted to only one level of parent/ancestors of the element. This is the main difference between the parent and parents method.
For Examples 1<html>…<body><div class=”one”><div class=”two”><p><span>Some text</span></p></div></div></body></html>$(‘span’).parent() will select the <p> tag such that the element set in the jQuery object is [span].
$(‘span’).parents() will select all parent tags such that the element set in the jQuery object is [p, div.two, div.one, body, html].
So parent() will select the first parent element while parents() will select all elements straight up the DOM tree.
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree. Also, $( "html" ).parent() method returns a set containing document whereas $( "html" ).parents() returns an empty set.
For Examples 2HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<div>
<p>
<a href="#" id="anchorTag">Click here</a>
</p>
</div>
</body>
</html>jQuery For parent() $('#anchorTag').parent(); //This would return p, immediate parent of a#anchorTag.jQuery For parents() $('#anchorTag').parents(); //This would return all the ancestors (p, div, body, html)
//On passing selector it will filter down the matched parent elements by selector
$('#anchorTag').parents('div'); //This would give me only div closest(selector) : It works like parents(), except that it returns only one parent/ancestor. This is ideal for the situation i mentioned earlier. If i want to check for existence of element in the ancestry tree, then i would prefer to use the closest rather than parents as it only target the selector rather than filtering it from all the ancestor elements. Here is example
$('#anchorTag').closest(); //This would give me empty object as we have not mentioned the selector
$('#anchorTag').closest('div'); //This would give me the div.