0

How to get the index number of a link? on clicking on the link? i have tried this code, to display the values

alert("i am script");
var an=[];
var href=[];
var atext=[] 
an = document.getElementsByTagName("a");
for(var i=0;i<an.length;i++)
{
    alert("i am inside for");
    href[i]=an[i].getAttribute("href");
    atext[i]=an[i].innerHTML;   
}
muthu
  • 11
  • 1

4 Answers4

0

With JavaScript way:

var links = document.getElementsByTagName('a');

for(var i = 0; i< links.length; i++){
  alert('index is: '+i+' link is: '+links[i].href);
}

jQuery Way:

var links = $('a');
$.each(links, function(index, link){ 
  alert('index is: '+index+' link is: '+$(link).attr('href'));
});
jayalalk
  • 2,382
  • 3
  • 17
  • 14
Dhanu Gurung
  • 8,480
  • 10
  • 47
  • 60
0

by javascript use document.links

var arr = [], l = document.links;
for(var i=0; i<l.length; i++) {
  arr.push(l[i].href);
}

reference get all the href attributes of a web site

Update TO get the index no

$("a").click(function(e){
e.preventDefault();

$(document).find("a").each(function(index,val){

alert("it is " + index + "  whose href is " +$(val).attr("href"));

});

});
Community
  • 1
  • 1
Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
0

You said "on clicking on the link" right? Here you have:

$("a").click(function(){
    var index = $(this).index();
    alert(index);
});

Cheers

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
0

Try this JavaScript:

Html:

<div id="xx">
<a href="#">link 1</a>
<a href="#">link 2</a>
<a href="#">link 3</a>
<a href="#">link 4</a>
</div>

javascript:

var g = document.getElementById('xx');
for (var i = 0, len = g.children.length; i < len; i++)
{ 
    (function(index){
        g.children[i].onclick = function(){
              alert(index)  ;
        }    
    })(i);

}
Mr.G
  • 3,413
  • 2
  • 16
  • 20