jQuery Selector How to - Select by attribute value








Question

We would like to know how to select by attribute value.

Answer


<!--from w  ww  . jav a 2s  .  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(){
          $("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: