views:

26

answers:

3

I'm trying to filter the XFN relationships meta data found in web pages. It is something like this:

<a href="site" rel="friend colleague" >Name</a>

in REL you can have various values, like "friend", "collegue" but even "me" and "met" because you can have multiple values, I did this:

xfn_me = $("a[rel*=me]").length;

But this doesn't work, because both "me" and "met" are matched! Is there a way to filter the values exactly, even when there are multiple values?

Thank you.

Please note that I have no control on the page, in fact I'm working on a Chrome extension, and this code should runs on any web page.

A: 

Since you are using jQuery, you could do it this way:

$('a[rel*=me]').filter(function(){ 
   return $.inArray('me', $(this).attr('rel').split(' ')) > -1;
}).length;

That basically finds all the a elements that might be a match, then filters them by splitting the rel tag into an array and checking the actual match is found.

Edit: I updated my code from !$.inArray to $.inArray > -1 as found by @UVL.

Doug Neiner
Thanks a lot, your code showed me the path to follow, but have found that only matches part of the values, because inarray returns the index of the item found, and negating (!) it returns incorrect values.Going to post the correct code below.
UVL
Thanks UVL, I updated my code as well.
Doug Neiner
A: 

A solution (until jquery 1.2 at least) is this:

xfn_me = $('a[rel*=me]').filter(function(){ 
 return $.inArray('me', $(this).attr('rel').split(' ')) > -1;
}).length;

Puts in xfn_me the number of A tags with rel matching "me", even when multiple rel values are used.

UVL
A: 

You could use the [attribute~=value] selector. It selects based on space-separated values exactly like how xfn and CSS classes work, i.e. [class~=className] is exactly the same as .className.

xfn_me = $("a[rel~=me]").length;

I couldn't find it in the jQuery documentation, but it works in 1.3 at least.

Matthew Crumley
Amazing! Thanks a lot, it really works despite it's missing from the jQuery documentation.
UVL
Woah! Very cool. I didn't know jQuery could do that. Here's hoping it makes it into the docs for 1.4
Doug Neiner