Change element id by using its own text value with attr and value returned from a function in jQuery

Description

The following code shows how to change element id by using its own text value with attr and value returned from a function.

Example


<html>
<head>
<script
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type='text/javascript'>
  $(document).ready(function() {<!--from   w w w .j a  v a2s.c  om-->
    $('li').attr('id', function() {
      return 'tmp' + $(this).text();
    });
  });
</script>
<style type='text/css'>
ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

ul li {
  margin: 3px;
  padding: 3px;
}

li#tmpA {
  background: #d7b05b;
}

li#tmpB {
  background: #d3988a;
}

li#tmpC {
  background: #8ad3a6;
}

li#tmpD {
  background: #8aa9d3;
}
</style>
</head>
<body>
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
  </ul>
</body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Example »




Animation
DOM
Event
Form
List
Select
Style
Table
Utilities