top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the difference between parent() and parents() methods in jQuery?

+2 votes
469 views
What is the difference between parent() and parents() methods in jQuery?
posted Jul 10, 2015 by Shivaranjini

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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.

answer Jul 10, 2015 by Amit Kumar Pandey
...