tags:

views:

107

answers:

2

I have two sets of elements with (sometimes) corresponding rel and id attributes:

<a rel="1" style="display:none"/>
<a rel="2" style="display:none"/>
<a rel="3" style="display:none"/>
and
<p id="1"/>
<p id="3"/>
<p id="chocolate"/>

I want an <a> element to appear when a <p> with a matching ID is loaded via a .get() request.

I figured I'd use filter(), but can't get it to work. I tried

  $('a').filter(function() {
    return $(this).attr('rel') == $('p').attr('id'); 
  }).show();

This seems to work on the the first element, but my understanding of filter() is that it should go through the whole list. Thanks.

+1  A: 

Try this:

$('a').each(function() {
    var $anchor = $(this);
    $('p').each(function() {
        if($(this).attr('id') == $anchor.attr('rel')) {
            $anchor.show();
        }
    });
});

I'm really not sure about the use of filter for what you're trying to do, maybe someone else can shed some light on that?

karim79
`filter` will work but he has to check against more than just the first paragraph element.
geowa4
Thanks, this worked perfectly. I like geowa4's suggestion, but I still need to check to see if there is a matching ID. I can't guarantee that a loaded element will match the element that I want to show. Thanks again!
andyashton
A: 

$('p').attr('id') will only ever return the ID of the first matched element. So your filter function will only ever return true if the anchor has the same rel attribute as the first paragraph found by jQuery. So you are right, in that filter will go through every anchor, but you aren't going through every paragraph.

When the paragraph is loaded, you know its ID. Therefore, you can just do this:

$('a[rel='+paragraphID+']').show();
geowa4