0

If I want to filter a set of links against an array and then style those not in the array as unavaible, how would I do that.

Here is what I have:

if (this.id == '93') {
     $links.filter(function() {

   }).addClass('unavailable');

But I don't know how the syntax for checking against an array.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
sehummel
  • 5,476
  • 24
  • 90
  • 137

1 Answers1

4

The short answer...

Use jQuery's $.inArray(value, array) function.

Also, see this Stackoverflow question, Javascript - array.contains(obj), whose answer mentions jQuery's $.inArray function as well as array searching functions in other JavaScript libraries.

The long answer...

I presume you have an collection of hyperlinks on your page, like so:

<p><a id="google" href="http://www.google.com/">Google</a></p>
<p><a id="yahoo" href="http://www.yahoo.com/">Yahoo!</a></p>
<p><a id="ask" href="http://www.ask.com/">Ask</a></p>
<p><a id="icerocket" href="http://www.icerocket.com/">Icerocket</a></p>

And that you have an array that contains the ids of those hyperlinks, like so:

var validLinkIds = ["google", "ask"];

The following script will filter across all <a> elements, "disabling" those that are not in the validLinkIds array:

$("a").filter(function() {
        if ($.inArray($(this).attr('id'), validLinkIds) < 0)
            $(this).removeAttr('href');
});

I created a JSFiddle entry where you can run/test out this script - http://jsfiddle.net/qMhWQ/

Happy Programming!

Community
  • 1
  • 1
Scott Mitchell
  • 8,659
  • 3
  • 55
  • 71