Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
theorise Avatar asked Feb 17 '11 11:02

theorise


5 Answers

You need this:

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

Check out the DEMO

like image 84
Sarfraz Avatar answered Oct 13 '22 02:10

Sarfraz


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');
});
like image 40
BoltClock Avatar answered Oct 13 '22 02:10

BoltClock


$(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.

like image 29
Gideon Avatar answered Oct 13 '22 01:10

Gideon


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

like image 29
TNC Avatar answered Oct 13 '22 03:10

TNC


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');
    });
});     
like image 35
user2514927 Avatar answered Oct 13 '22 02:10

user2514927