ドキュメント

Traversing/parent

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Traversing

parent[expr] )

Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
You may use an optional expression to filter the element(s). If there is no parent, returns a jQuery object with a length of 0.


To get or query all ancestor elements, consider closest or parents.
Arguments:
expr (Optional)String
An expression to filter the parent with.
Examples:

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

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $("*", document.body).each(function () {
      var parentTag = $(this).parent().get(0).tagName;
      $(this).prepend(document.createTextNode(parentTag + " > "));
    });

  });
  </script>
  <style>
  div,p { margin:10px; }
  </style>
</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>
</body>
</html>

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

$("p").parent(".selected").css("background", "yellow");

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("p").parent(".selected").css("background", "yellow");
  });
  </script>
  
</head>
<body>
  <div><p>Hello</p></div>
  <div class="selected"><p>Hello Again</p></div>

</body>
</html>

NameType