Boris
Boris

Reputation: 10244

How to differentiate two links with the same content using jQuery?

I have a page that contains two links with the same text "Add new item", but are targeting different URLs.

I created a javascript that uses jQuery library which references the link by its text. The code is:

var anchorElement = $("a:contains('Add new item')");

This is fine when I want to reference the first link. But, how do I reference the second one, being that they have the same text? Thanks.

Upvotes: 0

Views: 189

Answers (2)

ChristopheCVB
ChristopheCVB

Reputation: 7315

Try searching about filter or by iterating over them with each() Function.

Upvotes: 0

trapper
trapper

Reputation: 11993

To loop through use this

$("a:contains('Add new item')").each(function(){
    alert($(this).attr('href'));
});

You can also grab them by index

var first = $("a:contains('Add new item')").eq(0);
var second = $("a:contains('Add new item')").eq(1);

Upvotes: 1

Related Questions