Reputation: 26718
Suppose I have product links on a page, some products are within a recommendation div:
<a href="some_url?pid=abc"><img src ... ></a>
<a href="some_url?pid=abc">ABC Product Name...</a>
<a href="some_url?pid=def">
.... more product links
<div class="recommendations">
<a href="some_url?pid=uvw"> ...
<a href="some_url?pid=xyz"> ...
</div>
I need to construct unique list of pids for recommended and non-recommended urls like this:
recommended_pids = ["uvw","xyz"];
non_recommened_pids = ["abc","def"];
I know I can git the list of all pid on a page like this:
$('a[href*="pid="]').each(function() {
//get just the pid part
var link = this.href;
var pid = link.split('pid=')[1].split('&')[0];
pids.push(pid);
});
And I can get the list of recommended pids on a page using selector like this:
$('div.recommended a[href*="pid="]')
Sort and uniq each array then subtract all elements then do array subtraction to get the list of non-recommended pids.
But is there a way to use other jQuery filters to get the list of pids NOT contained within the recommended div without resorting to writing an array subtract function?
Upvotes: 0
Views: 1813
Reputation: 55678
Well, there's always .filter()
:
var $pidLinks = $('a[href*="pid="]');
// recommended links
$pidLinks.filter('div.recommendations > a');
// non-recommended links
$pidLinks.filter(':not(div.recommendations > a)');
For what it's worth, @Jayendra's solution is simpler and probably better, unless you need to get both lists - in which case I believe that using .filter()
should have better performance if you cache the original selection of all links.
Upvotes: 2
Reputation: 52779
Use not
$("a:not(.recommendations a)").each(function(index){
alert(this.id);
});
Upvotes: 2
Reputation: 15472
Inside the each function you could do this:
if( $(this).parents(".recommendations").length ) {
recommended_pids.push(pid);
} else {
non_recommened_pids.push(pid);
}
Upvotes: 1