Search code examples
javascriptjqueryselectorparent

Using filter() to filter jquery based on parents


I see on jquery documentation that I can use .parent() to filter my matched elements based on the parent. But in the process, the final result I get is the set of parent elements, not the original set of elements. So I see that I can use filter to achieve what I want. But I found so few documentation about how to use filter to filter based on the parent.

For example, my html is:

<div id="social">
    <a href="www.facebook.com">Facebook</a><br/>
    <a href="www.twitter.com">Twitter</a><br/>
</div>
<div id="topsites">
    <a href="www.facebook.com">Facebook</a><br/>
    <a href="stackoverflow.com">Stack Overflow</a><br/>
</div>

I want to get a set of elements, which consist of <a> tag that has facebook in it's href attribute, but within the social div parents.

I suspect the code will be something like this:

$('a[href*="facebook"]').filter( ... ).click(function() {

});

But I have absolutely no idea what to put on the filter. "parent#social" ?

Another way to put it is to use filter function.

$('a[href*="facebook"]').filter(function(index) {
    return ...
}
.click(function() {

});

I also don't know what code to put on the ... . Is it something like this.parent.id == "social" ? If possible, I prefer the first form, but if the solution can only be achieved by using the second form (filter function) then it's okay. Thank you very much.


Solution

  • I want to get a set of elements, which consist of <a> tag that has facebook in it's href attribute, but within the social div parents.

    No need of filter here,

    $('#social a[href*="facebook"]')
    

    will do.