Hello Readers,
parent() : this function travels only one level in the DOM tree.
parents() : this function search through the whole DOM tree.
For Example :
Given the following HTML :
<html>
<body>
<div class=one>
<div class=two>
<p><span>Some text</span></p>
</div>
</div>
</body>
</html>
In the above code if we want to find the span parent element then we have to use the code like below:
$('span').parent();
It will return [p] tag object.
Whereas if we call parents () method then we use the below code:
$('span').parents()
Then, we will get all the above element from current selected element such as jQuery object is [p, div.two, div.one, body, html]
But jquery also provide some filter method, also for filter the search means if we want to find only div element then you have to use the code like below.
$('span').parents().filter('div')
OR
$('span').parents('div')
This will result in [div.two, div.one].
If we want only first div in the parent DOM then we have to write code like below:
$('span').parents('div:eq(0)')
Result will be :
'div.two'
0 Comment(s)