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;
}
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'));
});
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"));
});
});
You said "on clicking on the link" right? Here you have:
$("a").click(function(){
var index = $(this).index();
alert(index);
});
Cheers
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.