Difference between jQuery parent() and parents() methods
In this post, we will see what is the difference between parent() and parents() methods. To understand this, let's look at the below given html code.
<html> <body> <form id="form1" runat="server"> <div id="dvParent"> <div id="dvChild"> <p><span id="spnText">jQuery By Example Rocks!!!</span> </p> </div> </div> </form> </body> </html>
As you see there 2 divs, 1 p and 1 span tag within the html code.
When you make a call to parent() function like
$("#spnText").parent()
will give you "P" as the output.parent() function selects the first parent in the DOM tree.
Now,if you call to parents() function like
$("#spnText").parents()
will give you all parents in DOM tree which are, p->dvChild->dvParent->form->body->html.
You can pass a filter in parents() function to select specific parent like if you want to select both the divs then
$("#spnText").parents('div')
The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.
Feel free to contact me for any help related to jQuery. I will gladly help you.