Javascript DOM How to - Set ID from function return and output id for each selected elements








Question

We would like to know how to set ID from function return and output id for each selected elements.

Answer


<!--  www. j  ava2  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").attr("id", function (arr) {
                return "div-id" + arr;
             });
             
             $("div").each(function () {
                $("span", this).html("(ID='" + this.id + "')");
             });
        });
    </script>
  </head>
  <body>
      <div><span></span></div>
  </body>
</html>

The code above is rendered as follows: