jQuery API

.parent()

.parent( [selector] ) Returns: jQuery

Description: Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

  • version added: 1.0.parent( [selector] )

    selectorA string containing a selector expression to match elements against.

Given a jQuery object that represents a set of DOM elements, the .parent() method allows us to search through the parents of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

Consider a page with a basic nested list on it:

<ul class="level-1">
  <li class="item-i">I</li>
  <li class="item-ii">II
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B
        <ul class="level-3">
          <li class="item-1">1</li>
          <li class="item-2">2</li>
          <li class="item-3">3</li>
        </ul>
      </li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

If we begin at item A, we can find its parents:

$('li.item-a').parent().css('background-color', 'red');

The result of this call is a red background for the level-2 list. Since we do not supply a selector expression, the parent element is unequivocally included as part of the object. If we had supplied one, the element would be tested for a match before it was included.

Examples:

Example: Shows the parent of each element as (parent > child). Check the View Source to see the raw html.

<!DOCTYPE html>
<html>
<head>
  <style>
  div,p { margin:10px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>div, 
    <span>span, </span>
    <b>b </b>

  </div>
  <p>p, 
    <span>span, 
      <em>em </em>
    </span>
  </p>

  <div>div, 
    <strong>strong, 
      <span>span, </span>
      <em>em, 
        <b>b, </b>
      </em>

    </strong>
    <b>b </b>
  </div>
<script>

    $("*", document.body).each(function () {
      var parentTag = $(this).parent().get(0).tagName;
      $(this).prepend(document.createTextNode(parentTag + " > "));
    });
</script>

</body>
</html>

Demo:

Example: Find the parent element of each paragraph with a class "selected".

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div><p>Hello</p></div>

  <div class="selected"><p>Hello Again</p></div>

<script>$("p").parent(".selected").css("background", "yellow");</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .parent() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .parent()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/bhuvidya bhu Boue vidya

    sometimes i wish that parent() also took a “number of levels to go backwards” parameter, so if you had to go three levels back, instead of parent().parent().parent() you could simply do parent(3) – this could really shorten some code lines….

    does anyone else agree?

  • Mark

    Funny. I looking on this page to see if that option was available. I guess not :)

    Currently my code looks like this

    $(this).parent().parent().parent().parent().parent().attr(‘id’)

    but would be nice to say

    $(this).parent(5).attr(‘id’)

  • EvilivE

    try parents() or parentsUntil() apply filter if needed, this should help

  • Eric

    Maybe adding an Id or a Class name to the parent element you are trying to reach would help.

    Try the following :

    $(this).parents(‘#parentId’)

    note the “s” in parents is important to navigate more then one level upward.

  • http://twitter.com/bhuvidya bhu Boue vidya

    yeh, there’s no doubt parents() can be very handy, but there are definitely times when i am nested in html which doesn’t have/need a lot of class/id markup, and i know exactly how far back the hierarchy i want to go – it actually makes more sense to me to think along the lines of ‘go up 3 levels’ than any other way

    i reckon a simple extension along the lines of:

    $.fn.parentn(n) {
    var $target = $(this[0]);
    for (var i=0; i<n && $target; i++) {
    $target = $target.parent();
    }
    return $target;
    }

    [bugger, i lost all indentation above]

    of course, this extension only considers the first element in the jquery obj is being targeted…..

  • Anonymous

    You can write

    $(this).parents().eq(4).attr(‘id’)

    Not as nice as parent(5) but definitely nicer than a chain of parent().
    Note that eq() returns the first element at index 0, so the 5th element is at index 4, like any array. This way you can also add a filtering espression or, since 1.4, pick from the end of the array with a negative index. really neat isn’t it?

  • http://www.fnews.co.il fnews

    parent is just one level. closest() looks up the tree like .parent
    ().parent()… until a match is found.. I'm not sure if there is an
    equivalent that would do what you want.. you could try .closest
    (“.parentClass”).find(“.childClass”)

  • http://www.hudin.com hudin

    What about if you want an element in the parent frame holding an iframe? I've been using parent.document.getElementById() Is there a faster or more direct method?

  • http://twitter.com/kisso699 Spyros Hajisavvas

    If you could add an ID to the parent element there wouldn't really be a reason for you to use .parents as they are unique and you'd use the selector, for classes though it may turn out to be quite useful.

  • http://twitter.com/dugokontov dugokontov

    - Removing my post for false info – (;

  • loubregand

    I think you should read documentation for method parents(): http://api.jquery.com/parents/
    Practically, it returns all the ancestors for the elements previously selected, in this case, it return ancestors (parent, parent of the parent, hos parent and so on until root node) of the 'this' element. Eq allow us to filter this chain of ancestors based on distance from the this node, so $(this).ancestors().eq(2) is the ancestor of distance 2, that is, the parent of the parent of the 'this' element.

  • loubregand

    I'd like to add, your code has a flaw: parent('.class-name') does not return the first parent which matches the selector, but will return the actual first-level parent of the current element only if it matches that selector. So, direct parent, or nothing at all.

  • http://twitter.com/dugokontov dugokontov

    My bad… You are absolutely right… didn't notice difference between parent() and parents().

    Removing my post for false info (;

  • http://twitter.com/dugokontov dugokontov

    the .parents() instead of .parent() will do the trick

  • Dsf

    dfgdf

  • https://www.google.com/accounts/o8/id?id=AItOawlYHmUOtJHeoIjVtmAyNIyP3XgOk-ue9gw Nyuszika7H

    Thanks so much! I learn a new thing every day. Today, I've learned the .parents() jQuery function.

  • Ian

    This is 7 months old however someone else might need the answer. Here is an easier way:

    $('#myelementid', parent.document).append();