jQuery Selector How to - Select elements that have the specified attribute








Question

We would like to know how to select elements that have the specified attribute.

Answer


<!--from w ww  .jav  a2 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>
      <div>no id</div>
      <div id="hey">with id</div>
  </body>
</html>

The code above is rendered as follows: