1

I am new to javascript/jquery:

If i have a lot of links - how can i select specific ones. For example if i have 1000 links, each consisting of hrefs and link text - and i want to select 5 specific links, what is the easiest way to do this ?

My current solution is like so:

var firstLink = $('.link_list a').filter(function() { 
        return $(this).text() === "Link One Text"; });
});
var secondLink = $('.link_list a').filter(function() { 
        return $(this).text() === "Link Two Text"; });
});

This is keeping in mind, I want to only select specific links, see Select link by text (exact match).

This seems a bit messy to have a lot of variables defined using the same filter function over and over. Any other ideas ?

Community
  • 1
  • 1
TABISH KHAN
  • 1,553
  • 1
  • 19
  • 32
  • `filter` creates an array, why don't you just use one loop, check the texts in a loop (use an array of texts) and return T/F correspondingly. After that you'll have references of all the wanted links in a single array. – Teemu Nov 21 '15 at 17:23

1 Answers1

0

turn it into a function?

function getLinkByText(text){
   return $('.link_list a').filter(function() { 
        return $(this).text() === text; });
   });
}

var firstLink = getLinkByText("Link One Text");
var secondLink = getLinkByText("Link Two Text");
BenG
  • 14,826
  • 5
  • 45
  • 60