0

I have following html

HTML code for testing purposes (do not submit uncommented):
<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>

My JS

$('a[id^=mm]').on('click', function () {
alert("test")
var as = document.body.getElementsByTagName("a");
alert("test")
for(var i=0; i < as.length;i++) {
  as[i].onClick = function(){
          alert(i);
  }
   }  
});

The alert is not giving me the index of the link clicked. How can i get the index?

Suyash
  • 331
  • 1
  • 4
  • 20
  • I think another part of the answer that's not a duplicate is you need quotes around `mm`: `$('a[id^="mm"]')` – Tashi Mar 30 '17 at 09:15

2 Answers2

1

use jquery with index() function

$('body').on('click','a[id^=mm]', function () {
console.log($(this).index()/2)

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HTML code for testing purposes (do not submit uncommented):

<body>
  In my life, I used the following web search engines:<br/>
  <a href="#test" id="mmYahooId">Yahoo!</a><br/>
  <a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
  <a href="#test" id="mmgooId">Google</a><br/>
</body>
prasanth
  • 22,145
  • 4
  • 29
  • 53
1

Try the following:

$('a[id^=mm]').on('click', function () {
    var nodeList = Array.prototype.slice.call(document.body.getElementsByTagName("a"));
    var index = nodeList.indexOf($(this)[0]);
    alert('You have clicked: '+index)
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In my life, I used the following web search engines:<br/>
<a href="#test" id="mmYahooId">Yahoo!</a><br/>
<a href="#test" id="mmaltaVistaId">AltaVista</a><br/>
<a href="#test" id="mmgooId">Google</a><br/>
Mamun
  • 66,969
  • 9
  • 47
  • 59