jQuery Method How to - Use text() to get the clicked element text








Question

We would like to know how to use text() to get the clicked element text.

Answer


<!-- w  ww.  j  av  a  2 s. c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.1.0.js'></script>
<script type='text/javascript'>
$(window).load(function(){
    $("a").click(function(){
        event.preventDefault();
        console.log($(this).text());
    });
});
</script>
</head>
<body>
  <a href="#1">link 1</a>
  <a href="#2">link 2</a>
  <a href="#3">link 3</a>
  
  <p>Check the console for output.</p>
  
</body>
</html>

The code above is rendered as follows: