ドキュメント

Traversing/closest

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Traversing

closest( expr )

New in jQuery 1.3 Get a set of elements containing the closest ancestor element that matches the specified selector, the starting element included.

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

Closest is especially useful for dealing with event delegation.

Arguments:
exprString
An expression to filter the elements with.
Examples:

Show how event delegation can be done with closest.

    $(document).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("hilight");
    });

<!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).bind("click", function (e) {
      $(e.target).closest("li").toggleClass("hilight");
    });

  });
  </script>
  <style>
  li { margin: 3px; padding: 3px; background: #EEEEEE; }
  li.hilight { background: yellow; }
  </style>
</head>
<body>
  <ul>
<li><b>Click me!</b></li>
<li>You can also <b>Click me!</b></li>
</ul>
</body>
</html>

NameType