jquery parents() method


  Translation results:

parents

UK ['peərənts] US ['peərənts]

n.Parents (plural noun of parent)

jquery parents() methodsyntax

Function: parents() obtains the ancestor elements of each element in the current matching element set. Filtering with a selector is optional.

Syntax: .parents(selector)

Parameters:

Parameter Description
selector String value, containing the selector expression used to match elements.

Description: If given a jQuery object that represents a collection of DOM elements, the .parents() method allows us to search for these elements in the DOM tree. Ancestor element and constructs a new jQuery object with the matching elements in ascending order from the nearest parent element. Elements are returned in order from the nearest parent outward. The .parents() method is similar to the .parent() method, except that the latter traverses a single level up the DOM tree. This method accepts an optional selector expression of the same type as the argument we passed into the $() function. If this selector is applied, elements will be filtered by testing whether they match the selector.

jquery parents() methodexample

<!DOCTYPE html>
<html>
<head>
  <style>
  b, span, p, html body {
    padding: .5em;
    border: 1px solid;
  }
  b { color:blue; }
  strong { color:red; }
  </style>
  <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
</head>

<body>
  <div>
    <p>
      <span>
        <b>我的父元素是:</b>
      </span>
    </p>
  </div>

<script>
var parentEls = $("b").parents()
            .map(function () { 
                  return this.tagName; 
                })
            .get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
</script>

</body>
</html>
Run instance »

Click the "Run instance" button to view the online instance

Home

Videos

Q&A