jQuery Event How to - Get nearby element from an event








Question

We would like to know how to get nearby element from an event.

Answer


<!--from   ww w.  j av  a2  s. c  o  m-->
<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: