jQuery .parents() gets the ancestors of each element in the current set of matched elements

Syntax and Description

.parents([selector])

gets the ancestors of each element in the current set of matched elements, optionally filtered by a selector. selector (optional) is a string containing a selector expression to match elements against. Its return value is the new jQuery object.

Count the parent elements by tag name

The following code gets DIV parent count


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from ww w . ja v  a 2s .  c om-->
             $("span").click(function () {
                 var len = $("span").parents("div").length;
                 alert(len);
             });
        });
    </script>
  </head>
  <body>
    <body>
        <div>
          <div><span>Hello ja va2s.com</span></div>
        </div>
  </body>
</html>

Click to view the demo

Map the parents

The following code gets parents and then uses the map function to get all of their tag names.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from   w  ww .  j  av a2 s .co  m-->
             var parentEls = $("span").parents()
                          .map(function () {
                                return this.tagName;
                              })
                          .get().join(", ");
             $("span").append(parentEls);
        });
    </script>
  </head>
  <body>
    <body>
       <div>
         <p>
          <span>
          </span>
         </p>
       </div>

  </body>
</html>

Click to view the demo

Find all unique div parent elements of each span

Click to find all unique div parent elements of each span.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w  w  w  .  j  a v  a2  s . c  o  m-->
    function showParents() {

              var len = $("span")
                               .parents("div")
                               .css("border", "2px red solid")
                               .length;
              $("b").text("Unique div parents: " + len);
            }
            $("span").click(function () {

              showParents();
            });
        });
    </script>
    <style>
      .selected { color:blue; }

    </style>

  </head>
  <body>
    <body>
        <div>
          <div><span>span</span></div>
          <span>span</span>
        </div>
        <div>
          <span>java2s.com</span>
        </div>
        <b></b>
    </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities