Iterating through elements and adding index number - Javascript jQuery

Javascript examples for jQuery:Number

Description

Iterating through elements and adding index number

Demo Code

ResultView the demo in separate window

<html>
 <head> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.js"></script> 
  <script type="text/javascript">
    $(window).load(function(){/*from w w  w  .  j  av  a2 s  .c o  m*/
$('h2[id^="id"]').click(function(index){
    var idx = $(this).index();
    $(this).addClass('hello' + idx)
});
    });

      </script> 
 </head> 
 <body> 
  <h2 id="id0">0</h2> 
  <h2 id="id1">1</h2> 
  <h2 id="id2">2</h2> 
  <h2 id="id3">3</h2>  
 </body>
</html>

Related Tutorials