theorise
theorise

Reputation: 7425

jQuery $(this).find not working

I am making an accordion with a long list of articles.

I have the jQuery working when I use the following, only it will slideUp/Down every article on the page:

$('article a').click(function() {
    $('article').find('h3').slideToggle('fast');
});

In theory this should work, but it doesn't do a thing:

$('article a').click(function() {
    $(this).find('h3').slideToggle('fast');
});

You can see a demo here: http://jsfiddle.net/CfqGG/

Where am I going wrong?

Upvotes: 11

Views: 60720

Answers (5)

user2514927
user2514927

Reputation: 11

Here is the updates code, check it out, you need specify the its sibling, cheers

$(document).ready(function() {    
    //hides articles
    $('article h3').hide();  
    //article accordian
    $('article a').click(function() {
        $(this).siblings('h3').slideToggle('fast');
    });
});     

Upvotes: 1

TNC
TNC

Reputation: 5386

In your code, $('article a') and subsequently $(this) is looking inside of the anchor.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382666

You need this:

$('article a').click(function() {
    $(this).closest('article').find('h3').slideToggle('fast');
});

Check out the DEMO

Upvotes: 5

BoltClock
BoltClock

Reputation: 723498

In theory that should not work because in your click event, this refers to the <a>, not the <article>, because your click event is bound to <a>.

Try this:

$('article a').click(function() {
    $(this).parent().find('h3').slideToggle('fast');
});

Upvotes: 19

Gideon
Gideon

Reputation: 18491

$(this).siblings('h3').slideToggle('fast');

this refers to the a element, and find searches an element in its descendants. h3 is not a descendant but a sibling.

Upvotes: 7

Related Questions