jQuery Method How to - Use attr('attribute name') to get the attribute name








Question

We would like to know how to use attr('attribute name') to get the attribute name.

Answer


<!--from www  .  j  av  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(){
          $("div[id]").one("click", function(){
              var idString = $(this).text() + " = " + $(this).attr("id");
              $(this).text(idString);
          });
    });
    </script>
  </head>
  <body>
      Click to see.
      <div>div</div>
      <div id="hey">div</div>
  </body>
</html>

The code above is rendered as follows: