Reputation: 3501
I'm trying to solve for two scenarios:
Identify if the link clicked exists already on the page.
Then if the link already exists, get the index() for the link clicked of the duplicate links.
My code is not working correctly since it's not identifying correctly if the link clicked is a duplicate and it's giving me an index of the sum of all links instead of the duplicate link.
$("a").click(function() {
Rank = $(this).index('a');
if($("a").attr("href") != $(this).attr("href")) {
alert('\nLink Rank '+Rank+'\n\nYes, this is duplicate link');
return false;
}
else {
alert('\nLink Rank '+Rank+'\n\nNo, this is NOT a duplicate link');
return false;
}
});
Demo: http://jsfiddle.net/no4gkk0n/1/
Upvotes: 1
Views: 347
Reputation: 337570
You can look for elements with the same attribute with the attribute selector: [href="foo"]
, then check the length
property. If it's more than 1, there is a duplicate link:
$("a").click(function (e) {
e.preventDefault();
Rank = $(this).index('a');
if ($("a[href='" + $(this).attr("href") + "']").length > 1) {
alert('\nLink Rank ' + Rank + '\n\nYes, this is duplicate link');
} else {
alert('\nLink Rank ' + Rank + '\n\nNo, this is NOT a duplicate link');
}
});
Upvotes: 4