Reputation: 548
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.
Upvotes: 1
Views: 521
Reputation: 41823
$('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();
Upvotes: 0
Reputation: 342655
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?
Upvotes: 1