jQuery Selector How to - Get nearby element








Question

We would like to know how to get nearby element.

Answer


<!-- w  w  w  . j  a  v a  2 s  .  c  om-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){
          $(document).bind("click", function (e) {
               $(e.target).closest("span").text("asdf");
          });
        });
    </script>
  </head>
  <body>
    <body>
         <div><span>span</span><span>span</span><span>span</span></div>
  </body>
</html>

The code above is rendered as follows: